diff --git a/dist/163.index.js b/dist/163.index.js new file mode 100644 index 00000000..f80cd43e --- /dev/null +++ b/dist/163.index.js @@ -0,0 +1,225 @@ +"use strict"; +exports.id = 163; +exports.ids = [163]; +exports.modules = { + +/***/ 26163: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var sharedIniFileLoader = __webpack_require__(93438); +var propertyProvider = __webpack_require__(1104); +var client = __webpack_require__(17582); + +const resolveCredentialSource = (credentialSource, profileName, logger) => { + const sourceProvidersMap = { + EcsContainer: async (options) => { + const { fromHttp } = await __webpack_require__.e(/* import() */ 795).then(__webpack_require__.bind(__webpack_require__, 60795)); + const { fromContainerMetadata } = await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 40566, 19)); + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => propertyProvider.chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, + Ec2InstanceMetadata: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 40566, 19)); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, + Environment: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 56104, 19)); + return async () => fromEnv(options)().then(setNamedProvider); + }, + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } + else { + throw new propertyProvider.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` + + `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger }); + } +}; +const setNamedProvider = (creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); + +const isAssumeRoleProfile = (arg, { profile = "default", logger } = {}) => { + return (Boolean(arg) && + typeof arg === "object" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && + ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && + ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && + (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger }))); +}; +const isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + } + return withSourceProfile; +}; +const isCredentialSourceProfile = (arg, { profile, logger }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + } + return withProviderProfile; +}; +const resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer } = await __webpack_require__.e(/* import() */ 58).then(__webpack_require__.t.bind(__webpack_require__, 31058, 23)); + options.roleAssumer = getDefaultRoleAssumer({ + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region, + }, + }, options.clientPlugins); + } + if (source_profile && source_profile in visitedProfiles) { + throw new propertyProvider.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` + + ` ${sharedIniFileLoader.getProfileName(options)}. Profiles visited: ` + + Object.keys(visitedProfiles).join(", "), { logger: options.logger }); + } + options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); + const sourceCredsProvider = source_profile + ? resolveProfileData(source_profile, profiles, options, { + ...visitedProfiles, + [source_profile]: true, + }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) + : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } + else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10), + }; + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); + } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); + } + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } +}; +const isCredentialSourceWithoutRoleArn = (section) => { + return !section.role_arn && !!section.credential_source; +}; + +const isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; +const resolveProcessCredentials = async (options, profile) => __webpack_require__.e(/* import() */ 630).then(__webpack_require__.t.bind(__webpack_require__, 15630, 19)).then(({ fromProcess }) => fromProcess({ + ...options, + profile, +})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); + +const resolveSsoCredentials = async (profile, profileData, options = {}) => { + const { fromSSO } = await __webpack_require__.e(/* import() */ 212).then(__webpack_require__.t.bind(__webpack_require__, 8212, 19)); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig, + })().then((creds) => { + if (profileData.sso_session) { + return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } + else { + return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + } + }); +}; +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const isStaticCredsProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.aws_access_key_id === "string" && + typeof arg.aws_secret_access_key === "string" && + ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && + ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; +const resolveStaticCredentials = async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }), + ...(profile.aws_account_id && { accountId: profile.aws_account_id }), + }; + return client.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); +}; + +const isWebIdentityProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.web_identity_token_file === "string" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; +const resolveWebIdentityCredentials = async (profile, options) => Promise.all(/* import() */[__webpack_require__.e(58), __webpack_require__.e(654)]).then(__webpack_require__.t.bind(__webpack_require__, 47654, 23)).then(({ fromTokenFile }) => fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig, +})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))); + +const resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); + } + if (isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isWebIdentityProfile(data)) { + return resolveWebIdentityCredentials(data, options); + } + if (isProcessProfile(data)) { + return resolveProcessCredentials(options, profileName); + } + if (isSsoProfile(data)) { + return await resolveSsoCredentials(profileName, data, options); + } + throw new propertyProvider.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); +}; + +const fromIni = (_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig, + }, + }; + init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + return resolveProfileData(sharedIniFileLoader.getProfileName({ + profile: _init.profile ?? callerClientConfig?.profile, + }), profiles, init); +}; + +exports.fromIni = fromIni; + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/212.index.js b/dist/212.index.js new file mode 100644 index 00000000..16c1a54c --- /dev/null +++ b/dist/212.index.js @@ -0,0 +1,1443 @@ +"use strict"; +exports.id = 212; +exports.ids = [212]; +exports.modules = { + +/***/ 50111: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; +const core_1 = __webpack_require__(91446); +const util_middleware_1 = __webpack_require__(30954); +const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccountRoles": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccounts": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "Logout": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 57321: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __webpack_require__(16158); +const util_endpoints_2 = __webpack_require__(79674); +const ruleset_1 = __webpack_require__(79170); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 79170: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; + + +/***/ }), + +/***/ 43628: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var middlewareHostHeader = __webpack_require__(25164); +var middlewareLogger = __webpack_require__(65832); +var middlewareRecursionDetection = __webpack_require__(39870); +var middlewareUserAgent = __webpack_require__(70997); +var configResolver = __webpack_require__(39316); +var core = __webpack_require__(22744); +var middlewareContentLength = __webpack_require__(47212); +var middlewareEndpoint = __webpack_require__(88205); +var middlewareRetry = __webpack_require__(19618); +var smithyClient = __webpack_require__(61411); +var httpAuthSchemeProvider = __webpack_require__(50111); +var runtimeConfig = __webpack_require__(88766); +var regionConfigResolver = __webpack_require__(26521); +var protocolHttp = __webpack_require__(13494); +var middlewareSerde = __webpack_require__(58305); +var core$1 = __webpack_require__(91446); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +class SSOServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOServiceException.prototype); + } +} + +class InvalidRequestException extends SSOServiceException { + name = "InvalidRequestException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + } +} +class ResourceNotFoundException extends SSOServiceException { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +} +class TooManyRequestsException extends SSOServiceException { + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsException.prototype); + } +} +class UnauthorizedException extends SSOServiceException { + name = "UnauthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedException.prototype); + } +} +const GetRoleCredentialsRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.accessToken && { accessToken: smithyClient.SENSITIVE_STRING }), +}); +const RoleCredentialsFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.secretAccessKey && { secretAccessKey: smithyClient.SENSITIVE_STRING }), + ...(obj.sessionToken && { sessionToken: smithyClient.SENSITIVE_STRING }), +}); +const GetRoleCredentialsResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }), +}); +const ListAccountRolesRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.accessToken && { accessToken: smithyClient.SENSITIVE_STRING }), +}); +const ListAccountsRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.accessToken && { accessToken: smithyClient.SENSITIVE_STRING }), +}); +const LogoutRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.accessToken && { accessToken: smithyClient.SENSITIVE_STRING }), +}); + +const se_GetRoleCredentialsCommand = async (input, context) => { + const b = core.requestBuilder(input, context); + const headers = smithyClient.map({}, smithyClient.isSerializableHeaderValue, { + [_xasbt]: input[_aT], + }); + b.bp("/federation/credentials"); + const query = smithyClient.map({ + [_rn]: [, smithyClient.expectNonNull(input[_rN], `roleName`)], + [_ai]: [, smithyClient.expectNonNull(input[_aI], `accountId`)], + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}; +const se_ListAccountRolesCommand = async (input, context) => { + const b = core.requestBuilder(input, context); + const headers = smithyClient.map({}, smithyClient.isSerializableHeaderValue, { + [_xasbt]: input[_aT], + }); + b.bp("/assignment/roles"); + const query = smithyClient.map({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], + [_ai]: [, smithyClient.expectNonNull(input[_aI], `accountId`)], + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}; +const se_ListAccountsCommand = async (input, context) => { + const b = core.requestBuilder(input, context); + const headers = smithyClient.map({}, smithyClient.isSerializableHeaderValue, { + [_xasbt]: input[_aT], + }); + b.bp("/assignment/accounts"); + const query = smithyClient.map({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}; +const se_LogoutCommand = async (input, context) => { + const b = core.requestBuilder(input, context); + const headers = smithyClient.map({}, smithyClient.isSerializableHeaderValue, { + [_xasbt]: input[_aT], + }); + b.bp("/logout"); + let body; + b.m("POST").h(headers).b(body); + return b.build(); +}; +const de_GetRoleCredentialsCommand = async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = smithyClient.map({ + $metadata: deserializeMetadata(output), + }); + const data = smithyClient.expectNonNull(smithyClient.expectObject(await core$1.parseJsonBody(output.body, context)), "body"); + const doc = smithyClient.take(data, { + roleCredentials: smithyClient._json, + }); + Object.assign(contents, doc); + return contents; +}; +const de_ListAccountRolesCommand = async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = smithyClient.map({ + $metadata: deserializeMetadata(output), + }); + const data = smithyClient.expectNonNull(smithyClient.expectObject(await core$1.parseJsonBody(output.body, context)), "body"); + const doc = smithyClient.take(data, { + nextToken: smithyClient.expectString, + roleList: smithyClient._json, + }); + Object.assign(contents, doc); + return contents; +}; +const de_ListAccountsCommand = async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = smithyClient.map({ + $metadata: deserializeMetadata(output), + }); + const data = smithyClient.expectNonNull(smithyClient.expectObject(await core$1.parseJsonBody(output.body, context)), "body"); + const doc = smithyClient.take(data, { + accountList: smithyClient._json, + nextToken: smithyClient.expectString, + }); + Object.assign(contents, doc); + return contents; +}; +const de_LogoutCommand = async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = smithyClient.map({ + $metadata: deserializeMetadata(output), + }); + await smithyClient.collectBody(output.body, context); + return contents; +}; +const de_CommandError = async (output, context) => { + const parsedOutput = { + ...output, + body: await core$1.parseJsonErrorBody(output.body, context), + }; + const errorCode = core$1.loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "InvalidRequestException": + case "com.amazonaws.sso#InvalidRequestException": + throw await de_InvalidRequestExceptionRes(parsedOutput); + case "ResourceNotFoundException": + case "com.amazonaws.sso#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput); + case "TooManyRequestsException": + case "com.amazonaws.sso#TooManyRequestsException": + throw await de_TooManyRequestsExceptionRes(parsedOutput); + case "UnauthorizedException": + case "com.amazonaws.sso#UnauthorizedException": + throw await de_UnauthorizedExceptionRes(parsedOutput); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode, + }); + } +}; +const throwDefaultError = smithyClient.withBaseException(SSOServiceException); +const de_InvalidRequestExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + message: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + message: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_TooManyRequestsExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + message: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new TooManyRequestsException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_UnauthorizedExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + message: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new UnauthorizedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); +const _aI = "accountId"; +const _aT = "accessToken"; +const _ai = "account_id"; +const _mR = "maxResults"; +const _mr = "max_result"; +const _nT = "nextToken"; +const _nt = "next_token"; +const _rN = "roleName"; +const _rn = "role_name"; +const _xasbt = "x-amz-sso_bearer_token"; + +class GetRoleCredentialsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("SWBPortalService", "GetRoleCredentials", {}) + .n("SSOClient", "GetRoleCredentialsCommand") + .f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog) + .ser(se_GetRoleCredentialsCommand) + .de(de_GetRoleCredentialsCommand) + .build() { +} + +class ListAccountRolesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("SWBPortalService", "ListAccountRoles", {}) + .n("SSOClient", "ListAccountRolesCommand") + .f(ListAccountRolesRequestFilterSensitiveLog, void 0) + .ser(se_ListAccountRolesCommand) + .de(de_ListAccountRolesCommand) + .build() { +} + +class ListAccountsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("SWBPortalService", "ListAccounts", {}) + .n("SSOClient", "ListAccountsCommand") + .f(ListAccountsRequestFilterSensitiveLog, void 0) + .ser(se_ListAccountsCommand) + .de(de_ListAccountsCommand) + .build() { +} + +class LogoutCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("SWBPortalService", "Logout", {}) + .n("SSOClient", "LogoutCommand") + .f(LogoutRequestFilterSensitiveLog, void 0) + .ser(se_LogoutCommand) + .de(de_LogoutCommand) + .build() { +} + +const commands = { + GetRoleCredentialsCommand, + ListAccountRolesCommand, + ListAccountsCommand, + LogoutCommand, +}; +class SSO extends SSOClient { +} +smithyClient.createAggregatedClient(commands, SSO); + +const paginateListAccountRoles = core.createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAccounts = core.createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); + +Object.defineProperty(exports, "$Command", ({ + enumerable: true, + get: function () { return smithyClient.Command; } +})); +Object.defineProperty(exports, "__Client", ({ + enumerable: true, + get: function () { return smithyClient.Client; } +})); +exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; +exports.GetRoleCredentialsRequestFilterSensitiveLog = GetRoleCredentialsRequestFilterSensitiveLog; +exports.GetRoleCredentialsResponseFilterSensitiveLog = GetRoleCredentialsResponseFilterSensitiveLog; +exports.InvalidRequestException = InvalidRequestException; +exports.ListAccountRolesCommand = ListAccountRolesCommand; +exports.ListAccountRolesRequestFilterSensitiveLog = ListAccountRolesRequestFilterSensitiveLog; +exports.ListAccountsCommand = ListAccountsCommand; +exports.ListAccountsRequestFilterSensitiveLog = ListAccountsRequestFilterSensitiveLog; +exports.LogoutCommand = LogoutCommand; +exports.LogoutRequestFilterSensitiveLog = LogoutRequestFilterSensitiveLog; +exports.ResourceNotFoundException = ResourceNotFoundException; +exports.RoleCredentialsFilterSensitiveLog = RoleCredentialsFilterSensitiveLog; +exports.SSO = SSO; +exports.SSOClient = SSOClient; +exports.SSOServiceException = SSOServiceException; +exports.TooManyRequestsException = TooManyRequestsException; +exports.UnauthorizedException = UnauthorizedException; +exports.paginateListAccountRoles = paginateListAccountRoles; +exports.paginateListAccounts = paginateListAccounts; + + +/***/ }), + +/***/ 88766: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const tslib_1 = __webpack_require__(61860); +const package_json_1 = tslib_1.__importDefault(__webpack_require__(36948)); +const core_1 = __webpack_require__(91446); +const util_user_agent_node_1 = __webpack_require__(9082); +const config_resolver_1 = __webpack_require__(39316); +const hash_node_1 = __webpack_require__(5092); +const middleware_retry_1 = __webpack_require__(19618); +const node_config_provider_1 = __webpack_require__(61814); +const node_http_handler_1 = __webpack_require__(95493); +const util_body_length_node_1 = __webpack_require__(13638); +const util_retry_1 = __webpack_require__(15518); +const runtimeConfig_shared_1 = __webpack_require__(35831); +const smithy_client_1 = __webpack_require__(61411); +const util_defaults_mode_node_1 = __webpack_require__(15435); +const smithy_client_2 = __webpack_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 35831: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __webpack_require__(91446); +const core_2 = __webpack_require__(22744); +const smithy_client_1 = __webpack_require__(61411); +const url_parser_1 = __webpack_require__(85792); +const util_base64_1 = __webpack_require__(82763); +const util_utf8_1 = __webpack_require__(85339); +const httpAuthSchemeProvider_1 = __webpack_require__(50111); +const endpointResolver_1 = __webpack_require__(57321); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 7321: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var protocolHttp = __webpack_require__(13494); +var core = __webpack_require__(22744); +var propertyProvider = __webpack_require__(1104); +var client = __webpack_require__(17582); +var signatureV4 = __webpack_require__(75118); + +const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const resolveAwsSdkSigV4Config = (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = core.normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => core.normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await core.normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + }); + return resolvedConfig; +}; +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.validateSigningProperties = validateSigningProperties; + + +/***/ }), + +/***/ 8212: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; + + +var propertyProvider = __webpack_require__(1104); +var sharedIniFileLoader = __webpack_require__(93438); +var client = __webpack_require__(17582); +var tokenProviders = __webpack_require__(88967); + +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const SHOULD_FAIL_CREDENTIAL_CHAIN = false; +const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await tokenProviders.fromSso({ + profile, + filepath, + configFilepath, + ignoreCache, + })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString(), + }; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + else { + try { + token = await sharedIniFileLoader.getSSOTokenFromFile(ssoStartUrl); + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { accessToken } = token; + const { SSOClient, GetRoleCredentialsCommand } = await Promise.resolve().then(function () { return __webpack_require__(11031); }); + const sso = ssoClient || + new SSOClient(Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion, + })); + let ssoResp; + try { + ssoResp = await sso.send(new GetRoleCredentialsCommand({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken, + })); + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new propertyProvider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + if (ssoSession) { + client.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); + } + else { + client.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + } + return credentials; +}; + +const validateSsoProfile = (profile, logger) => { + const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; + if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { + throw new propertyProvider.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + + `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger }); + } + return profile; +}; + +const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); + } + if (!isSsoProfile(profile)) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger, + }); + } + if (profile?.sso_session) { + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); + const session = ssoSessions[profile.sso_session]; + const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; + if (ssoRegion && ssoRegion !== session.sso_region) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + profile.sso_region = session.sso_region; + profile.sso_start_url = session.sso_start_url; + } + const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient: ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } + else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new propertyProvider.CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + + '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init.logger }); + } + else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } +}; + +exports.fromSSO = fromSSO; +__webpack_unused_export__ = isSsoProfile; +__webpack_unused_export__ = validateSsoProfile; + + +/***/ }), + +/***/ 11031: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var clientSso = __webpack_require__(43628); + + + +Object.defineProperty(exports, "GetRoleCredentialsCommand", ({ + enumerable: true, + get: function () { return clientSso.GetRoleCredentialsCommand; } +})); +Object.defineProperty(exports, "SSOClient", ({ + enumerable: true, + get: function () { return clientSso.SSOClient; } +})); + + +/***/ }), + +/***/ 88967: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var client = __webpack_require__(17582); +var httpAuthSchemes = __webpack_require__(7321); +var propertyProvider = __webpack_require__(1104); +var sharedIniFileLoader = __webpack_require__(93438); +var fs = __webpack_require__(79896); + +const fromEnvSigningName = ({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); + } + const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName); + if (!(bearerTokenKey in process.env)) { + throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); + } + const token = { token: process.env[bearerTokenKey] }; + client.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}; + +const EXPIRE_WINDOW_MS = 5 * 60 * 1000; +const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +const getSsoOidcClient = async (ssoRegion, init = {}) => { + const { SSOOIDCClient } = await __webpack_require__.e(/* import() */ 477).then(__webpack_require__.t.bind(__webpack_require__, 54477, 19)); + const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger, + })); + return ssoOidcClient; +}; + +const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}) => { + const { CreateTokenCommand } = await __webpack_require__.e(/* import() */ 477).then(__webpack_require__.t.bind(__webpack_require__, 54477, 19)); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); + return ssoOidcClient.send(new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token", + })); +}; + +const validateTokenExpiry = (token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); + } +}; + +const validateTokenKey = (key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); + } +}; + +const { writeFile } = fs.promises; +const writeSSOTokenToFile = (id, ssoToken) => { + const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}; + +const lastRefreshAttemptTime = new Date(0); +const fromSso = (_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig, + }, + }; + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + const profileName = sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } + else if (!profile["sso_session"]) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); + } + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); + } + } + ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName); + } + catch (e) { + throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken, + }); + } + catch (error) { + } + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration, + }; + } + catch (error) { + validateTokenExpiry(existingToken); + return existingToken; + } +}; + +const fromStatic = ({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}; + +const nodeProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init), async () => { + throw new propertyProvider.TokenProviderError("Could not load token from any providers", false); +}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); + +exports.fromEnvSigningName = fromEnvSigningName; +exports.fromSso = fromSso; +exports.fromStatic = fromStatic; +exports.nodeProvider = nodeProvider; + + +/***/ }), + +/***/ 36948: +/***/ ((module) => { + +module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/client-sso","description":"AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native","version":"3.908.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-sso","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo sso"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.908.0","@aws-sdk/middleware-host-header":"3.901.0","@aws-sdk/middleware-logger":"3.901.0","@aws-sdk/middleware-recursion-detection":"3.901.0","@aws-sdk/middleware-user-agent":"3.908.0","@aws-sdk/region-config-resolver":"3.901.0","@aws-sdk/types":"3.901.0","@aws-sdk/util-endpoints":"3.901.0","@aws-sdk/util-user-agent-browser":"3.907.0","@aws-sdk/util-user-agent-node":"3.908.0","@smithy/config-resolver":"^4.3.0","@smithy/core":"^3.15.0","@smithy/fetch-http-handler":"^5.3.1","@smithy/hash-node":"^4.2.0","@smithy/invalid-dependency":"^4.2.0","@smithy/middleware-content-length":"^4.2.0","@smithy/middleware-endpoint":"^4.3.1","@smithy/middleware-retry":"^4.4.1","@smithy/middleware-serde":"^4.2.0","@smithy/middleware-stack":"^4.2.0","@smithy/node-config-provider":"^4.3.0","@smithy/node-http-handler":"^4.3.0","@smithy/protocol-http":"^5.3.0","@smithy/smithy-client":"^4.7.1","@smithy/types":"^4.6.0","@smithy/url-parser":"^4.2.0","@smithy/util-base64":"^4.3.0","@smithy/util-body-length-browser":"^4.2.0","@smithy/util-body-length-node":"^4.2.1","@smithy/util-defaults-mode-browser":"^4.3.0","@smithy/util-defaults-mode-node":"^4.2.1","@smithy/util-endpoints":"^3.2.0","@smithy/util-middleware":"^4.2.0","@smithy/util-retry":"^4.2.0","@smithy/util-utf8":"^4.2.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-sso"}}'); + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/477.index.js b/dist/477.index.js new file mode 100644 index 00000000..4d32ef39 --- /dev/null +++ b/dist/477.index.js @@ -0,0 +1,856 @@ +"use strict"; +exports.id = 477; +exports.ids = [477]; +exports.modules = { + +/***/ 8014: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; +const core_1 = __webpack_require__(91446); +const util_middleware_1 = __webpack_require__(30954); +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 42936: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __webpack_require__(16158); +const util_endpoints_2 = __webpack_require__(79674); +const ruleset_1 = __webpack_require__(67605); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 67605: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; + + +/***/ }), + +/***/ 54477: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; + + +var middlewareHostHeader = __webpack_require__(25164); +var middlewareLogger = __webpack_require__(65832); +var middlewareRecursionDetection = __webpack_require__(39870); +var middlewareUserAgent = __webpack_require__(70997); +var configResolver = __webpack_require__(39316); +var core = __webpack_require__(22744); +var middlewareContentLength = __webpack_require__(47212); +var middlewareEndpoint = __webpack_require__(88205); +var middlewareRetry = __webpack_require__(19618); +var smithyClient = __webpack_require__(61411); +var httpAuthSchemeProvider = __webpack_require__(8014); +var runtimeConfig = __webpack_require__(22791); +var regionConfigResolver = __webpack_require__(26521); +var protocolHttp = __webpack_require__(13494); +var middlewareSerde = __webpack_require__(58305); +var core$1 = __webpack_require__(91446); + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOOIDCClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +class SSOOIDCServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOOIDCServiceException.prototype); + } +} + +const AccessDeniedExceptionReason = { + KMS_ACCESS_DENIED: "KMS_AccessDeniedException", +}; +class AccessDeniedException extends SSOOIDCServiceException { + name = "AccessDeniedException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class AuthorizationPendingException extends SSOOIDCServiceException { + name = "AuthorizationPendingException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +const CreateTokenRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.clientSecret && { clientSecret: smithyClient.SENSITIVE_STRING }), + ...(obj.refreshToken && { refreshToken: smithyClient.SENSITIVE_STRING }), + ...(obj.codeVerifier && { codeVerifier: smithyClient.SENSITIVE_STRING }), +}); +const CreateTokenResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.accessToken && { accessToken: smithyClient.SENSITIVE_STRING }), + ...(obj.refreshToken && { refreshToken: smithyClient.SENSITIVE_STRING }), + ...(obj.idToken && { idToken: smithyClient.SENSITIVE_STRING }), +}); +class ExpiredTokenException extends SSOOIDCServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InternalServerException extends SSOOIDCServiceException { + name = "InternalServerException"; + $fault = "server"; + error; + error_description; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidClientException extends SSOOIDCServiceException { + name = "InvalidClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidGrantException extends SSOOIDCServiceException { + name = "InvalidGrantException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +const InvalidRequestExceptionReason = { + KMS_DISABLED_KEY: "KMS_DisabledException", + KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", + KMS_INVALID_STATE: "KMS_InvalidStateException", + KMS_KEY_NOT_FOUND: "KMS_NotFoundException", +}; +class InvalidRequestException extends SSOOIDCServiceException { + name = "InvalidRequestException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class InvalidScopeException extends SSOOIDCServiceException { + name = "InvalidScopeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class SlowDownException extends SSOOIDCServiceException { + name = "SlowDownException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnauthorizedClientException extends SSOOIDCServiceException { + name = "UnauthorizedClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnsupportedGrantTypeException extends SSOOIDCServiceException { + name = "UnsupportedGrantTypeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} + +const se_CreateTokenCommand = async (input, context) => { + const b = core.requestBuilder(input, context); + const headers = { + "content-type": "application/json", + }; + b.bp("/token"); + let body; + body = JSON.stringify(smithyClient.take(input, { + clientId: [], + clientSecret: [], + code: [], + codeVerifier: [], + deviceCode: [], + grantType: [], + redirectUri: [], + refreshToken: [], + scope: (_) => smithyClient._json(_), + })); + b.m("POST").h(headers).b(body); + return b.build(); +}; +const de_CreateTokenCommand = async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = smithyClient.map({ + $metadata: deserializeMetadata(output), + }); + const data = smithyClient.expectNonNull(smithyClient.expectObject(await core$1.parseJsonBody(output.body, context)), "body"); + const doc = smithyClient.take(data, { + accessToken: smithyClient.expectString, + expiresIn: smithyClient.expectInt32, + idToken: smithyClient.expectString, + refreshToken: smithyClient.expectString, + tokenType: smithyClient.expectString, + }); + Object.assign(contents, doc); + return contents; +}; +const de_CommandError = async (output, context) => { + const parsedOutput = { + ...output, + body: await core$1.parseJsonErrorBody(output.body, context), + }; + const errorCode = core$1.loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "AccessDeniedException": + case "com.amazonaws.ssooidc#AccessDeniedException": + throw await de_AccessDeniedExceptionRes(parsedOutput); + case "AuthorizationPendingException": + case "com.amazonaws.ssooidc#AuthorizationPendingException": + throw await de_AuthorizationPendingExceptionRes(parsedOutput); + case "ExpiredTokenException": + case "com.amazonaws.ssooidc#ExpiredTokenException": + throw await de_ExpiredTokenExceptionRes(parsedOutput); + case "InternalServerException": + case "com.amazonaws.ssooidc#InternalServerException": + throw await de_InternalServerExceptionRes(parsedOutput); + case "InvalidClientException": + case "com.amazonaws.ssooidc#InvalidClientException": + throw await de_InvalidClientExceptionRes(parsedOutput); + case "InvalidGrantException": + case "com.amazonaws.ssooidc#InvalidGrantException": + throw await de_InvalidGrantExceptionRes(parsedOutput); + case "InvalidRequestException": + case "com.amazonaws.ssooidc#InvalidRequestException": + throw await de_InvalidRequestExceptionRes(parsedOutput); + case "InvalidScopeException": + case "com.amazonaws.ssooidc#InvalidScopeException": + throw await de_InvalidScopeExceptionRes(parsedOutput); + case "SlowDownException": + case "com.amazonaws.ssooidc#SlowDownException": + throw await de_SlowDownExceptionRes(parsedOutput); + case "UnauthorizedClientException": + case "com.amazonaws.ssooidc#UnauthorizedClientException": + throw await de_UnauthorizedClientExceptionRes(parsedOutput); + case "UnsupportedGrantTypeException": + case "com.amazonaws.ssooidc#UnsupportedGrantTypeException": + throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode, + }); + } +}; +const throwDefaultError = smithyClient.withBaseException(SSOOIDCServiceException); +const de_AccessDeniedExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + reason: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new AuthorizationPendingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_ExpiredTokenExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_InternalServerExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_InvalidClientExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InvalidClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_InvalidGrantExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InvalidGrantException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_InvalidRequestExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + reason: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_InvalidScopeExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new InvalidScopeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_SlowDownExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new SlowDownException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new UnauthorizedClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => { + const contents = smithyClient.map({}); + const data = parsedOutput.body; + const doc = smithyClient.take(data, { + error: smithyClient.expectString, + error_description: smithyClient.expectString, + }); + Object.assign(contents, doc); + const exception = new UnsupportedGrantTypeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return smithyClient.decorateServiceException(exception, parsedOutput.body); +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +class CreateTokenCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AWSSSOOIDCService", "CreateToken", {}) + .n("SSOOIDCClient", "CreateTokenCommand") + .f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog) + .ser(se_CreateTokenCommand) + .de(de_CreateTokenCommand) + .build() { +} + +const commands = { + CreateTokenCommand, +}; +class SSOOIDC extends SSOOIDCClient { +} +smithyClient.createAggregatedClient(commands, SSOOIDC); + +__webpack_unused_export__ = ({ + enumerable: true, + get: function () { return smithyClient.Command; } +}); +__webpack_unused_export__ = ({ + enumerable: true, + get: function () { return smithyClient.Client; } +}); +__webpack_unused_export__ = AccessDeniedException; +__webpack_unused_export__ = AccessDeniedExceptionReason; +__webpack_unused_export__ = AuthorizationPendingException; +exports.CreateTokenCommand = CreateTokenCommand; +__webpack_unused_export__ = CreateTokenRequestFilterSensitiveLog; +__webpack_unused_export__ = CreateTokenResponseFilterSensitiveLog; +__webpack_unused_export__ = ExpiredTokenException; +__webpack_unused_export__ = InternalServerException; +__webpack_unused_export__ = InvalidClientException; +__webpack_unused_export__ = InvalidGrantException; +__webpack_unused_export__ = InvalidRequestException; +__webpack_unused_export__ = InvalidRequestExceptionReason; +__webpack_unused_export__ = InvalidScopeException; +__webpack_unused_export__ = SSOOIDC; +exports.SSOOIDCClient = SSOOIDCClient; +__webpack_unused_export__ = SSOOIDCServiceException; +__webpack_unused_export__ = SlowDownException; +__webpack_unused_export__ = UnauthorizedClientException; +__webpack_unused_export__ = UnsupportedGrantTypeException; + + +/***/ }), + +/***/ 22791: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const tslib_1 = __webpack_require__(61860); +const package_json_1 = tslib_1.__importDefault(__webpack_require__(77507)); +const core_1 = __webpack_require__(91446); +const util_user_agent_node_1 = __webpack_require__(9082); +const config_resolver_1 = __webpack_require__(39316); +const hash_node_1 = __webpack_require__(5092); +const middleware_retry_1 = __webpack_require__(19618); +const node_config_provider_1 = __webpack_require__(61814); +const node_http_handler_1 = __webpack_require__(95493); +const util_body_length_node_1 = __webpack_require__(13638); +const util_retry_1 = __webpack_require__(15518); +const runtimeConfig_shared_1 = __webpack_require__(13892); +const smithy_client_1 = __webpack_require__(61411); +const util_defaults_mode_node_1 = __webpack_require__(15435); +const smithy_client_2 = __webpack_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 13892: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __webpack_require__(91446); +const core_2 = __webpack_require__(22744); +const smithy_client_1 = __webpack_require__(61411); +const url_parser_1 = __webpack_require__(85792); +const util_base64_1 = __webpack_require__(82763); +const util_utf8_1 = __webpack_require__(85339); +const httpAuthSchemeProvider_1 = __webpack_require__(8014); +const endpointResolver_1 = __webpack_require__(42936); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 77507: +/***/ ((module) => { + +module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.908.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"sideEffects":false,"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.908.0","@aws-sdk/middleware-host-header":"3.901.0","@aws-sdk/middleware-logger":"3.901.0","@aws-sdk/middleware-recursion-detection":"3.901.0","@aws-sdk/middleware-user-agent":"3.908.0","@aws-sdk/region-config-resolver":"3.901.0","@aws-sdk/types":"3.901.0","@aws-sdk/util-endpoints":"3.901.0","@aws-sdk/util-user-agent-browser":"3.907.0","@aws-sdk/util-user-agent-node":"3.908.0","@smithy/config-resolver":"^4.3.0","@smithy/core":"^3.15.0","@smithy/fetch-http-handler":"^5.3.1","@smithy/hash-node":"^4.2.0","@smithy/invalid-dependency":"^4.2.0","@smithy/middleware-content-length":"^4.2.0","@smithy/middleware-endpoint":"^4.3.1","@smithy/middleware-retry":"^4.4.1","@smithy/middleware-serde":"^4.2.0","@smithy/middleware-stack":"^4.2.0","@smithy/node-config-provider":"^4.3.0","@smithy/node-http-handler":"^4.3.0","@smithy/protocol-http":"^5.3.0","@smithy/smithy-client":"^4.7.1","@smithy/types":"^4.6.0","@smithy/url-parser":"^4.2.0","@smithy/util-base64":"^4.3.0","@smithy/util-body-length-browser":"^4.2.0","@smithy/util-body-length-node":"^4.2.1","@smithy/util-defaults-mode-browser":"^4.3.0","@smithy/util-defaults-mode-node":"^4.2.1","@smithy/util-endpoints":"^3.2.0","@smithy/util-middleware":"^4.2.0","@smithy/util-retry":"^4.2.0","@smithy/util-utf8":"^4.2.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/505.index.js b/dist/505.index.js new file mode 100644 index 00000000..1709a618 --- /dev/null +++ b/dist/505.index.js @@ -0,0 +1,226 @@ +"use strict"; +exports.id = 505; +exports.ids = [505]; +exports.modules = { + +/***/ 97505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var utilUtf8 = __webpack_require__(85339); + +class EventStreamSerde { + marshaller; + serializer; + deserializer; + serdeContext; + defaultContentType; + constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + unionSchema.getMemberSchemas(); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType }, + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body, + }; + } + for await (const page of eventStream) { + yield page; + } + }, + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body, + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders, + }; + return { + headers, + body, + }; + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject, + }; + } + else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body), + }; + } + else { + return { + $unknown: event, + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; + } + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } + } + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + }, + }; + } + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = (() => { + const struct = unionSchema.getSchema(); + return struct.memberNames.includes(unionMember); + })(); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(15, value); + } + else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } + else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } + else { + type = "long"; + } + } + else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } + else if (memberSchema.isStringSchema()) { + type = "string"; + } + else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value, + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } + else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } + else { + serializer.write(eventSchema, event[unionMember]); + } + } + else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" + ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization) + : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders, + }; + } +} + +exports.EventStreamSerde = EventStreamSerde; + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/58.index.js b/dist/58.index.js new file mode 100644 index 00000000..4c69205c --- /dev/null +++ b/dist/58.index.js @@ -0,0 +1,1224 @@ +"use strict"; +exports.id = 58; +exports.ids = [58]; +exports.modules = { + +/***/ 56001: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = __webpack_require__(25164); +const middleware_logger_1 = __webpack_require__(65832); +const middleware_recursion_detection_1 = __webpack_require__(39870); +const middleware_user_agent_1 = __webpack_require__(70997); +const config_resolver_1 = __webpack_require__(39316); +const core_1 = __webpack_require__(22744); +const middleware_content_length_1 = __webpack_require__(47212); +const middleware_endpoint_1 = __webpack_require__(88205); +const middleware_retry_1 = __webpack_require__(19618); +const smithy_client_1 = __webpack_require__(61411); +Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); +const httpAuthSchemeProvider_1 = __webpack_require__(5037); +const EndpointParameters_1 = __webpack_require__(64361); +const runtimeConfig_1 = __webpack_require__(18452); +const runtimeExtensions_1 = __webpack_require__(83488); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); + } + destroy() { + super.destroy(); + } +} +exports.STSClient = STSClient; + + +/***/ }), + +/***/ 54710: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; + + +/***/ }), + +/***/ 5037: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = __webpack_require__(91446); +const util_middleware_1 = __webpack_require__(30954); +const STSClient_1 = __webpack_require__(56001); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 64361: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + + +/***/ }), + +/***/ 35075: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __webpack_require__(16158); +const util_endpoints_2 = __webpack_require__(79674); +const ruleset_1 = __webpack_require__(79144); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 79144: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ruleSet = void 0; +const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; +const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "String" }, n = { [F]: true, "default": false, [G]: "Boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; +const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; +exports.ruleSet = _data; + + +/***/ }), + +/***/ 31058: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var STSClient = __webpack_require__(56001); +var smithyClient = __webpack_require__(61411); +var middlewareEndpoint = __webpack_require__(88205); +var middlewareSerde = __webpack_require__(58305); +var EndpointParameters = __webpack_require__(64361); +var core = __webpack_require__(91446); +var protocolHttp = __webpack_require__(13494); +var client = __webpack_require__(17582); + +class STSServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, STSServiceException.prototype); + } +} + +const CredentialsFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.SecretAccessKey && { SecretAccessKey: smithyClient.SENSITIVE_STRING }), +}); +const AssumeRoleResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }), +}); +class ExpiredTokenException extends STSServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + } +} +class MalformedPolicyDocumentException extends STSServiceException { + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); + } +} +class PackedPolicyTooLargeException extends STSServiceException { + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); + } +} +class RegionDisabledException extends STSServiceException { + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, RegionDisabledException.prototype); + } +} +class IDPRejectedClaimException extends STSServiceException { + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); + } +} +class InvalidIdentityTokenException extends STSServiceException { + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); + } +} +const AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.WebIdentityToken && { WebIdentityToken: smithyClient.SENSITIVE_STRING }), +}); +const AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }), +}); +class IDPCommunicationErrorException extends STSServiceException { + name = "IDPCommunicationErrorException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); + } +} + +const se_AssumeRoleCommand = async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleRequest(input), + [_A]: _AR, + [_V]: _, + }); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_AssumeRoleWithWebIdentityCommand = async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithWebIdentityRequest(input), + [_A]: _ARWWI, + [_V]: _, + }); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const de_AssumeRoleCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core.parseXmlBody(output.body, context); + let contents = {}; + contents = de_AssumeRoleResponse(data.AssumeRoleResult); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_AssumeRoleWithWebIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core.parseXmlBody(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_CommandError = async (output, context) => { + const parsedOutput = { + ...output, + body: await core.parseXmlErrorBody(output.body, context), + }; + const errorCode = loadQueryErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "ExpiredTokenException": + case "com.amazonaws.sts#ExpiredTokenException": + throw await de_ExpiredTokenExceptionRes(parsedOutput); + case "MalformedPolicyDocument": + case "com.amazonaws.sts#MalformedPolicyDocumentException": + throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput); + case "PackedPolicyTooLarge": + case "com.amazonaws.sts#PackedPolicyTooLargeException": + throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput); + case "RegionDisabledException": + case "com.amazonaws.sts#RegionDisabledException": + throw await de_RegionDisabledExceptionRes(parsedOutput); + case "IDPCommunicationError": + case "com.amazonaws.sts#IDPCommunicationErrorException": + throw await de_IDPCommunicationErrorExceptionRes(parsedOutput); + case "IDPRejectedClaim": + case "com.amazonaws.sts#IDPRejectedClaimException": + throw await de_IDPRejectedClaimExceptionRes(parsedOutput); + case "InvalidIdentityToken": + case "com.amazonaws.sts#InvalidIdentityTokenException": + throw await de_InvalidIdentityTokenExceptionRes(parsedOutput); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody: parsedBody.Error, + errorCode, + }); + } +}; +const de_ExpiredTokenExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_ExpiredTokenException(body.Error); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPCommunicationErrorException(body.Error); + const exception = new IDPCommunicationErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPRejectedClaimException(body.Error); + const exception = new IDPRejectedClaimException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidIdentityTokenException(body.Error); + const exception = new InvalidIdentityTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_MalformedPolicyDocumentException(body.Error); + const exception = new MalformedPolicyDocumentException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_PackedPolicyTooLargeException(body.Error); + const exception = new PackedPolicyTooLargeException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_RegionDisabledExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_RegionDisabledException(body.Error); + const exception = new RegionDisabledException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const se_AssumeRoleRequest = (input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; + } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA]); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T]); + if (input[_T]?.length === 0) { + entries.Tags = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; + }); + } + if (input[_TTK] != null) { + const memberEntries = se_tagKeyListType(input[_TTK]); + if (input[_TTK]?.length === 0) { + entries.TransitiveTagKeys = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TransitiveTagKeys.${key}`; + entries[loc] = value; + }); + } + if (input[_EI] != null) { + entries[_EI] = input[_EI]; + } + if (input[_SN] != null) { + entries[_SN] = input[_SN]; + } + if (input[_TC] != null) { + entries[_TC] = input[_TC]; + } + if (input[_SI] != null) { + entries[_SI] = input[_SI]; + } + if (input[_PC] != null) { + const memberEntries = se_ProvidedContextsListType(input[_PC]); + if (input[_PC]?.length === 0) { + entries.ProvidedContexts = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `ProvidedContexts.${key}`; + entries[loc] = value; + }); + } + return entries; +}; +const se_AssumeRoleWithWebIdentityRequest = (input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; + } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_WIT] != null) { + entries[_WIT] = input[_WIT]; + } + if (input[_PI] != null) { + entries[_PI] = input[_PI]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA]); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + return entries; +}; +const se_policyDescriptorListType = (input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; + } + const memberEntries = se_PolicyDescriptorType(entry); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}; +const se_PolicyDescriptorType = (input, context) => { + const entries = {}; + if (input[_a] != null) { + entries[_a] = input[_a]; + } + return entries; +}; +const se_ProvidedContext = (input, context) => { + const entries = {}; + if (input[_PAr] != null) { + entries[_PAr] = input[_PAr]; + } + if (input[_CA] != null) { + entries[_CA] = input[_CA]; + } + return entries; +}; +const se_ProvidedContextsListType = (input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; + } + const memberEntries = se_ProvidedContext(entry); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}; +const se_Tag = (input, context) => { + const entries = {}; + if (input[_K] != null) { + entries[_K] = input[_K]; + } + if (input[_Va] != null) { + entries[_Va] = input[_Va]; + } + return entries; +}; +const se_tagKeyListType = (input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; + } + entries[`member.${counter}`] = entry; + counter++; + } + return entries; +}; +const se_tagListType = (input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; + } + const memberEntries = se_Tag(entry); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}; +const de_AssumedRoleUser = (output, context) => { + const contents = {}; + if (output[_ARI] != null) { + contents[_ARI] = smithyClient.expectString(output[_ARI]); + } + if (output[_Ar] != null) { + contents[_Ar] = smithyClient.expectString(output[_Ar]); + } + return contents; +}; +const de_AssumeRoleResponse = (output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C]); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU]); + } + if (output[_PPS] != null) { + contents[_PPS] = smithyClient.strictParseInt32(output[_PPS]); + } + if (output[_SI] != null) { + contents[_SI] = smithyClient.expectString(output[_SI]); + } + return contents; +}; +const de_AssumeRoleWithWebIdentityResponse = (output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C]); + } + if (output[_SFWIT] != null) { + contents[_SFWIT] = smithyClient.expectString(output[_SFWIT]); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU]); + } + if (output[_PPS] != null) { + contents[_PPS] = smithyClient.strictParseInt32(output[_PPS]); + } + if (output[_Pr] != null) { + contents[_Pr] = smithyClient.expectString(output[_Pr]); + } + if (output[_Au] != null) { + contents[_Au] = smithyClient.expectString(output[_Au]); + } + if (output[_SI] != null) { + contents[_SI] = smithyClient.expectString(output[_SI]); + } + return contents; +}; +const de_Credentials = (output, context) => { + const contents = {}; + if (output[_AKI] != null) { + contents[_AKI] = smithyClient.expectString(output[_AKI]); + } + if (output[_SAK] != null) { + contents[_SAK] = smithyClient.expectString(output[_SAK]); + } + if (output[_ST] != null) { + contents[_ST] = smithyClient.expectString(output[_ST]); + } + if (output[_E] != null) { + contents[_E] = smithyClient.expectNonNull(smithyClient.parseRfc3339DateTimeWithOffset(output[_E])); + } + return contents; +}; +const de_ExpiredTokenException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_IDPCommunicationErrorException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_IDPRejectedClaimException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_InvalidIdentityTokenException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_MalformedPolicyDocumentException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_PackedPolicyTooLargeException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const de_RegionDisabledException = (output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = smithyClient.expectString(output[_m]); + } + return contents; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); +const throwDefaultError = smithyClient.withBaseException(STSServiceException); +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers, + }; + if (body !== undefined) { + contents.body = body; + } + return new protocolHttp.HttpRequest(contents); +}; +const SHARED_HEADERS = { + "content-type": "application/x-www-form-urlencoded", +}; +const _ = "2011-06-15"; +const _A = "Action"; +const _AKI = "AccessKeyId"; +const _AR = "AssumeRole"; +const _ARI = "AssumedRoleId"; +const _ARU = "AssumedRoleUser"; +const _ARWWI = "AssumeRoleWithWebIdentity"; +const _Ar = "Arn"; +const _Au = "Audience"; +const _C = "Credentials"; +const _CA = "ContextAssertion"; +const _DS = "DurationSeconds"; +const _E = "Expiration"; +const _EI = "ExternalId"; +const _K = "Key"; +const _P = "Policy"; +const _PA = "PolicyArns"; +const _PAr = "ProviderArn"; +const _PC = "ProvidedContexts"; +const _PI = "ProviderId"; +const _PPS = "PackedPolicySize"; +const _Pr = "Provider"; +const _RA = "RoleArn"; +const _RSN = "RoleSessionName"; +const _SAK = "SecretAccessKey"; +const _SFWIT = "SubjectFromWebIdentityToken"; +const _SI = "SourceIdentity"; +const _SN = "SerialNumber"; +const _ST = "SessionToken"; +const _T = "Tags"; +const _TC = "TokenCode"; +const _TTK = "TransitiveTagKeys"; +const _V = "Version"; +const _Va = "Value"; +const _WIT = "WebIdentityToken"; +const _a = "arn"; +const _m = "message"; +const buildFormUrlencodedString = (formEntries) => Object.entries(formEntries) + .map(([key, value]) => smithyClient.extendedEncodeURIComponent(key) + "=" + smithyClient.extendedEncodeURIComponent(value)) + .join("&"); +const loadQueryErrorCode = (output, data) => { + if (data.Error?.Code !== undefined) { + return data.Error.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}; + +class AssumeRoleCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}) + .n("STSClient", "AssumeRoleCommand") + .f(void 0, AssumeRoleResponseFilterSensitiveLog) + .ser(se_AssumeRoleCommand) + .de(de_AssumeRoleCommand) + .build() { +} + +class AssumeRoleWithWebIdentityCommand extends smithyClient.Command + .classBuilder() + .ep(EndpointParameters.commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}) + .n("STSClient", "AssumeRoleWithWebIdentityCommand") + .f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog) + .ser(se_AssumeRoleWithWebIdentityCommand) + .de(de_AssumeRoleWithWebIdentityCommand) + .build() { +} + +const commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand, +}; +class STS extends STSClient.STSClient { +} +smithyClient.createAggregatedClient(commands, STS); + +const ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } + } + return undefined; +}; +const resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`); + return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; +}; +const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + profile: stsOptions?.parentClientConfig?.profile, + credentialDefaultProvider: () => async () => closureSourceCreds, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}; +const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + profile: stsOptions?.parentClientConfig?.profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + if (accountId) { + client.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}; +const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}; + +const getCustomizableStsClientCtor = (baseCtor, customizations) => { + if (!customizations) + return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}; +const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); +const decorateDefaultCredentialProvider = (provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), + ...input, +}); + +Object.defineProperty(exports, "$Command", ({ + enumerable: true, + get: function () { return smithyClient.Command; } +})); +exports.AssumeRoleCommand = AssumeRoleCommand; +exports.AssumeRoleResponseFilterSensitiveLog = AssumeRoleResponseFilterSensitiveLog; +exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; +exports.AssumeRoleWithWebIdentityRequestFilterSensitiveLog = AssumeRoleWithWebIdentityRequestFilterSensitiveLog; +exports.AssumeRoleWithWebIdentityResponseFilterSensitiveLog = AssumeRoleWithWebIdentityResponseFilterSensitiveLog; +exports.CredentialsFilterSensitiveLog = CredentialsFilterSensitiveLog; +exports.ExpiredTokenException = ExpiredTokenException; +exports.IDPCommunicationErrorException = IDPCommunicationErrorException; +exports.IDPRejectedClaimException = IDPRejectedClaimException; +exports.InvalidIdentityTokenException = InvalidIdentityTokenException; +exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException; +exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException; +exports.RegionDisabledException = RegionDisabledException; +exports.STS = STS; +exports.STSServiceException = STSServiceException; +exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; +exports.getDefaultRoleAssumer = getDefaultRoleAssumer; +exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; +Object.keys(STSClient).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return STSClient[k]; } + }); +}); + + +/***/ }), + +/***/ 18452: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const tslib_1 = __webpack_require__(61860); +const package_json_1 = tslib_1.__importDefault(__webpack_require__(77507)); +const core_1 = __webpack_require__(91446); +const util_user_agent_node_1 = __webpack_require__(9082); +const config_resolver_1 = __webpack_require__(39316); +const core_2 = __webpack_require__(22744); +const hash_node_1 = __webpack_require__(5092); +const middleware_retry_1 = __webpack_require__(19618); +const node_config_provider_1 = __webpack_require__(61814); +const node_http_handler_1 = __webpack_require__(95493); +const util_body_length_node_1 = __webpack_require__(13638); +const util_retry_1 = __webpack_require__(15518); +const runtimeConfig_shared_1 = __webpack_require__(79730); +const smithy_client_1 = __webpack_require__(61411); +const util_defaults_mode_node_1 = __webpack_require__(15435); +const smithy_client_2 = __webpack_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 79730: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __webpack_require__(91446); +const core_2 = __webpack_require__(22744); +const smithy_client_1 = __webpack_require__(61411); +const url_parser_1 = __webpack_require__(85792); +const util_base64_1 = __webpack_require__(82763); +const util_utf8_1 = __webpack_require__(85339); +const httpAuthSchemeProvider_1 = __webpack_require__(5037); +const endpointResolver_1 = __webpack_require__(35075); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "STS", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 83488: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveRuntimeExtensions = void 0; +const region_config_resolver_1 = __webpack_require__(26521); +const protocol_http_1 = __webpack_require__(13494); +const smithy_client_1 = __webpack_require__(61411); +const httpAuthExtensionConfiguration_1 = __webpack_require__(54710); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; + + +/***/ }), + +/***/ 77507: +/***/ ((module) => { + +module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.908.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"sideEffects":false,"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.908.0","@aws-sdk/middleware-host-header":"3.901.0","@aws-sdk/middleware-logger":"3.901.0","@aws-sdk/middleware-recursion-detection":"3.901.0","@aws-sdk/middleware-user-agent":"3.908.0","@aws-sdk/region-config-resolver":"3.901.0","@aws-sdk/types":"3.901.0","@aws-sdk/util-endpoints":"3.901.0","@aws-sdk/util-user-agent-browser":"3.907.0","@aws-sdk/util-user-agent-node":"3.908.0","@smithy/config-resolver":"^4.3.0","@smithy/core":"^3.15.0","@smithy/fetch-http-handler":"^5.3.1","@smithy/hash-node":"^4.2.0","@smithy/invalid-dependency":"^4.2.0","@smithy/middleware-content-length":"^4.2.0","@smithy/middleware-endpoint":"^4.3.1","@smithy/middleware-retry":"^4.4.1","@smithy/middleware-serde":"^4.2.0","@smithy/middleware-stack":"^4.2.0","@smithy/node-config-provider":"^4.3.0","@smithy/node-http-handler":"^4.3.0","@smithy/protocol-http":"^5.3.0","@smithy/smithy-client":"^4.7.1","@smithy/types":"^4.6.0","@smithy/url-parser":"^4.2.0","@smithy/util-base64":"^4.3.0","@smithy/util-body-length-browser":"^4.2.0","@smithy/util-body-length-node":"^4.2.1","@smithy/util-defaults-mode-browser":"^4.3.0","@smithy/util-defaults-mode-node":"^4.2.1","@smithy/util-endpoints":"^3.2.0","@smithy/util-middleware":"^4.2.0","@smithy/util-retry":"^4.2.0","@smithy/util-utf8":"^4.2.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/630.index.js b/dist/630.index.js new file mode 100644 index 00000000..4dbfc535 --- /dev/null +++ b/dist/630.index.js @@ -0,0 +1,93 @@ +"use strict"; +exports.id = 630; +exports.ids = [630]; +exports.modules = { + +/***/ 15630: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var sharedIniFileLoader = __webpack_require__(93438); +var propertyProvider = __webpack_require__(1104); +var child_process = __webpack_require__(35317); +var util = __webpack_require__(39023); +var client = __webpack_require__(17582); + +const getValidatedProcessCredentials = (profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); + } + if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data.Expiration) { + const currentTime = new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); + } + } + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; + } + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...(data.SessionToken && { sessionToken: data.SessionToken }), + ...(data.Expiration && { expiration: new Date(data.Expiration) }), + ...(data.CredentialScope && { credentialScope: data.CredentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}; + +const resolveProcessCredentials = async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== undefined) { + const execPromise = util.promisify(sharedIniFileLoader.externalDataInterceptor?.getTokenRecord?.().exec ?? child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } + catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } + catch (error) { + throw new propertyProvider.CredentialsProviderError(error.message, { logger }); + } + } + else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + } + } + else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger, + }); + } +}; + +const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init); + return resolveProcessCredentials(sharedIniFileLoader.getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }), profiles, init.logger); +}; + +exports.fromProcess = fromProcess; + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/654.index.js b/dist/654.index.js new file mode 100644 index 00000000..7083c5d8 --- /dev/null +++ b/dist/654.index.js @@ -0,0 +1,143 @@ +"use strict"; +exports.id = 654; +exports.ids = [654]; +exports.modules = { + +/***/ 77753: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromTokenFile = void 0; +const client_1 = __webpack_require__(17582); +const property_provider_1 = __webpack_require__(1104); +const shared_ini_file_loader_1 = __webpack_require__(93438); +const fs_1 = __webpack_require__(79896); +const fromWebToken_1 = __webpack_require__(92543); +const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; +const ENV_ROLE_ARN = "AWS_ROLE_ARN"; +const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; +const fromTokenFile = (init = {}) => async () => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); + } + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init, + webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? + (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + return credentials; +}; +exports.fromTokenFile = fromTokenFile; + + +/***/ }), + +/***/ 92543: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromWebToken = void 0; +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__webpack_require__(31058))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); +}; +exports.fromWebToken = fromWebToken; + + +/***/ }), + +/***/ 47654: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +var fromTokenFile = __webpack_require__(77753); +var fromWebToken = __webpack_require__(92543); + + + +Object.keys(fromTokenFile).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromTokenFile[k]; } + }); +}); +Object.keys(fromWebToken).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromWebToken[k]; } + }); +}); + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/795.index.js b/dist/795.index.js new file mode 100644 index 00000000..26bceadb --- /dev/null +++ b/dist/795.index.js @@ -0,0 +1,234 @@ +"use strict"; +exports.id = 795; +exports.ids = [795]; +exports.modules = { + +/***/ 24815: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkUrl = void 0; +const property_provider_1 = __webpack_require__(1104); +const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; +const LOOPBACK_CIDR_IPv6 = "::1/128"; +const ECS_CONTAINER_HOST = "169.254.170.2"; +const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; +const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; +const checkUrl = (url, logger) => { + if (url.protocol === "https:") { + return; + } + if (url.hostname === ECS_CONTAINER_HOST || + url.hostname === EKS_CONTAINER_HOST_IPv4 || + url.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url.hostname.includes("[")) { + if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } + else { + if (url.hostname === "localhost") { + return; + } + const ipComponents = url.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && + inRange(ipComponents[1]) && + inRange(ipComponents[2]) && + inRange(ipComponents[3]) && + ipComponents.length === 4) { + return; + } + } + throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); +}; +exports.checkUrl = checkUrl; + + +/***/ }), + +/***/ 57030: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromHttp = void 0; +const tslib_1 = __webpack_require__(61860); +const client_1 = __webpack_require__(17582); +const node_http_handler_1 = __webpack_require__(95493); +const property_provider_1 = __webpack_require__(1104); +const promises_1 = tslib_1.__importDefault(__webpack_require__(91943)); +const checkUrl_1 = __webpack_require__(24815); +const requestHelpers_1 = __webpack_require__(94604); +const retry_wrapper_1 = __webpack_require__(98692); +const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; +const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn + ? console.warn + : options.logger.warn.bind(options.logger); + if (relative && full) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsFullUri will take precedence."); + } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationToken will take precedence."); + } + if (full) { + host = full; + } + else if (relative) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; + } + else { + throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url = new URL(host); + (0, checkUrl_1.checkUrl)(url, options.logger); + const requestHandler = node_http_handler_1.NodeHttpHandler.create({ + requestTimeout: options.timeout ?? 1000, + connectionTimeout: options.timeout ?? 1000, + }); + return (0, retry_wrapper_1.retryWrapper)(async () => { + const request = (0, requestHelpers_1.createGetRequest)(url); + if (token) { + request.headers.Authorization = token; + } + else if (tokenFile) { + request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + } + try { + const result = await requestHandler.handle(request); + return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + } + catch (e) { + throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1000); +}; +exports.fromHttp = fromHttp; + + +/***/ }), + +/***/ 94604: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createGetRequest = createGetRequest; +exports.getCredentials = getCredentials; +const property_provider_1 = __webpack_require__(1104); +const protocol_http_1 = __webpack_require__(13494); +const smithy_client_1 = __webpack_require__(61411); +const util_stream_1 = __webpack_require__(71914); +function createGetRequest(url) { + return new protocol_http_1.HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: Number(url.port), + path: url.pathname, + query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { + acc[k] = v; + return acc; + }, {}), + fragment: url.hash, + }); +} +async function getCredentials(response, logger) { + const stream = (0, util_stream_1.sdkStreamMixin)(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || + typeof parsed.SecretAccessKey !== "string" || + typeof parsed.Token !== "string" || + typeof parsed.Expiration !== "string") { + throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), + }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } + catch (e) { } + throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { + Code: parsedBody.Code, + Message: parsedBody.Message, + }); + } + throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); +} + + +/***/ }), + +/***/ 98692: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.retryWrapper = void 0; +const retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i = 0; i < maxRetries; ++i) { + try { + return await toRetry(); + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return await toRetry(); + }; +}; +exports.retryWrapper = retryWrapper; + + +/***/ }), + +/***/ 60795: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ value: true }); +exports.fromHttp = void 0; +var fromHttp_1 = __webpack_require__(57030); +Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); + + +/***/ }) + +}; +; \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 3f318e5b..b9ddba68 100644 --- a/dist/index.js +++ b/dist/index.js @@ -17172,22316 +17172,4999 @@ exports.ruleSet = _data; /***/ }), /***/ 80212: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AccessDeniedException: () => AccessDeniedException, - AgentUpdateStatus: () => AgentUpdateStatus, - ApplicationProtocol: () => ApplicationProtocol, - AssignPublicIp: () => AssignPublicIp, - AttributeLimitExceededException: () => AttributeLimitExceededException, - AvailabilityZoneRebalancing: () => AvailabilityZoneRebalancing, - BlockedException: () => BlockedException, - CPUArchitecture: () => CPUArchitecture, - CapacityProviderField: () => CapacityProviderField, - CapacityProviderStatus: () => CapacityProviderStatus, - CapacityProviderUpdateStatus: () => CapacityProviderUpdateStatus, - ClientException: () => ClientException, - ClusterContainsContainerInstancesException: () => ClusterContainsContainerInstancesException, - ClusterContainsServicesException: () => ClusterContainsServicesException, - ClusterContainsTasksException: () => ClusterContainsTasksException, - ClusterField: () => ClusterField, - ClusterNotFoundException: () => ClusterNotFoundException, - ClusterSettingName: () => ClusterSettingName, - Compatibility: () => Compatibility, - ConflictException: () => ConflictException, - Connectivity: () => Connectivity, - ContainerCondition: () => ContainerCondition, - ContainerInstanceField: () => ContainerInstanceField, - ContainerInstanceStatus: () => ContainerInstanceStatus, - CreateCapacityProviderCommand: () => CreateCapacityProviderCommand, - CreateClusterCommand: () => CreateClusterCommand, - CreateServiceCommand: () => CreateServiceCommand, - CreateTaskSetCommand: () => CreateTaskSetCommand, - DeleteAccountSettingCommand: () => DeleteAccountSettingCommand, - DeleteAttributesCommand: () => DeleteAttributesCommand, - DeleteCapacityProviderCommand: () => DeleteCapacityProviderCommand, - DeleteClusterCommand: () => DeleteClusterCommand, - DeleteServiceCommand: () => DeleteServiceCommand, - DeleteTaskDefinitionsCommand: () => DeleteTaskDefinitionsCommand, - DeleteTaskSetCommand: () => DeleteTaskSetCommand, - DeploymentControllerType: () => DeploymentControllerType, - DeploymentLifecycleHookStage: () => DeploymentLifecycleHookStage, - DeploymentRolloutState: () => DeploymentRolloutState, - DeploymentStrategy: () => DeploymentStrategy, - DeregisterContainerInstanceCommand: () => DeregisterContainerInstanceCommand, - DeregisterTaskDefinitionCommand: () => DeregisterTaskDefinitionCommand, - DescribeCapacityProvidersCommand: () => DescribeCapacityProvidersCommand, - DescribeClustersCommand: () => DescribeClustersCommand, - DescribeContainerInstancesCommand: () => DescribeContainerInstancesCommand, - DescribeServiceDeploymentsCommand: () => DescribeServiceDeploymentsCommand, - DescribeServiceRevisionsCommand: () => DescribeServiceRevisionsCommand, - DescribeServicesCommand: () => DescribeServicesCommand, - DescribeTaskDefinitionCommand: () => DescribeTaskDefinitionCommand, - DescribeTaskSetsCommand: () => DescribeTaskSetsCommand, - DescribeTasksCommand: () => DescribeTasksCommand, - DesiredStatus: () => DesiredStatus, - DeviceCgroupPermission: () => DeviceCgroupPermission, - DiscoverPollEndpointCommand: () => DiscoverPollEndpointCommand, - EBSResourceType: () => EBSResourceType, - ECS: () => ECS, - ECSClient: () => ECSClient, - ECSServiceException: () => ECSServiceException, - EFSAuthorizationConfigIAM: () => EFSAuthorizationConfigIAM, - EFSTransitEncryption: () => EFSTransitEncryption, - EnvironmentFileType: () => EnvironmentFileType, - ExecuteCommandCommand: () => ExecuteCommandCommand, - ExecuteCommandLogging: () => ExecuteCommandLogging, - ExecuteCommandResponseFilterSensitiveLog: () => ExecuteCommandResponseFilterSensitiveLog, - FirelensConfigurationType: () => FirelensConfigurationType, - GetTaskProtectionCommand: () => GetTaskProtectionCommand, - HealthStatus: () => HealthStatus, - InstanceHealthCheckState: () => InstanceHealthCheckState, - InstanceHealthCheckType: () => InstanceHealthCheckType, - InvalidParameterException: () => InvalidParameterException, - IpcMode: () => IpcMode, - LaunchType: () => LaunchType, - LimitExceededException: () => LimitExceededException, - ListAccountSettingsCommand: () => ListAccountSettingsCommand, - ListAttributesCommand: () => ListAttributesCommand, - ListClustersCommand: () => ListClustersCommand, - ListContainerInstancesCommand: () => ListContainerInstancesCommand, - ListServiceDeploymentsCommand: () => ListServiceDeploymentsCommand, - ListServicesByNamespaceCommand: () => ListServicesByNamespaceCommand, - ListServicesCommand: () => ListServicesCommand, - ListTagsForResourceCommand: () => ListTagsForResourceCommand, - ListTaskDefinitionFamiliesCommand: () => ListTaskDefinitionFamiliesCommand, - ListTaskDefinitionsCommand: () => ListTaskDefinitionsCommand, - ListTasksCommand: () => ListTasksCommand, - LogDriver: () => LogDriver, - ManagedAgentName: () => ManagedAgentName, - ManagedDraining: () => ManagedDraining, - ManagedScalingStatus: () => ManagedScalingStatus, - ManagedTerminationProtection: () => ManagedTerminationProtection, - MissingVersionException: () => MissingVersionException, - NamespaceNotFoundException: () => NamespaceNotFoundException, - NetworkMode: () => NetworkMode, - NoUpdateAvailableException: () => NoUpdateAvailableException, - OSFamily: () => OSFamily, - PidMode: () => PidMode, - PlacementConstraintType: () => PlacementConstraintType, - PlacementStrategyType: () => PlacementStrategyType, - PlatformDeviceType: () => PlatformDeviceType, - PlatformTaskDefinitionIncompatibilityException: () => PlatformTaskDefinitionIncompatibilityException, - PlatformUnknownException: () => PlatformUnknownException, - PropagateTags: () => PropagateTags, - ProxyConfigurationType: () => ProxyConfigurationType, - PutAccountSettingCommand: () => PutAccountSettingCommand, - PutAccountSettingDefaultCommand: () => PutAccountSettingDefaultCommand, - PutAttributesCommand: () => PutAttributesCommand, - PutClusterCapacityProvidersCommand: () => PutClusterCapacityProvidersCommand, - RegisterContainerInstanceCommand: () => RegisterContainerInstanceCommand, - RegisterTaskDefinitionCommand: () => RegisterTaskDefinitionCommand, - ResourceInUseException: () => ResourceInUseException, - ResourceNotFoundException: () => ResourceNotFoundException, - ResourceType: () => ResourceType, - RunTaskCommand: () => RunTaskCommand, - ScaleUnit: () => ScaleUnit, - SchedulingStrategy: () => SchedulingStrategy, - Scope: () => Scope, - ServerException: () => ServerException, - ServiceDeploymentLifecycleStage: () => ServiceDeploymentLifecycleStage, - ServiceDeploymentNotFoundException: () => ServiceDeploymentNotFoundException, - ServiceDeploymentRollbackMonitorsStatus: () => ServiceDeploymentRollbackMonitorsStatus, - ServiceDeploymentStatus: () => ServiceDeploymentStatus, - ServiceField: () => ServiceField, - ServiceNotActiveException: () => ServiceNotActiveException, - ServiceNotFoundException: () => ServiceNotFoundException, - SessionFilterSensitiveLog: () => SessionFilterSensitiveLog, - SettingName: () => SettingName, - SettingType: () => SettingType, - SortOrder: () => SortOrder, - StabilityStatus: () => StabilityStatus, - StartTaskCommand: () => StartTaskCommand, - StopServiceDeploymentCommand: () => StopServiceDeploymentCommand, - StopServiceDeploymentStopType: () => StopServiceDeploymentStopType, - StopTaskCommand: () => StopTaskCommand, - SubmitAttachmentStateChangesCommand: () => SubmitAttachmentStateChangesCommand, - SubmitContainerStateChangeCommand: () => SubmitContainerStateChangeCommand, - SubmitTaskStateChangeCommand: () => SubmitTaskStateChangeCommand, - TagResourceCommand: () => TagResourceCommand, - TargetNotConnectedException: () => TargetNotConnectedException, - TargetNotFoundException: () => TargetNotFoundException, - TargetType: () => TargetType, - TaskDefinitionFamilyStatus: () => TaskDefinitionFamilyStatus, - TaskDefinitionField: () => TaskDefinitionField, - TaskDefinitionPlacementConstraintType: () => TaskDefinitionPlacementConstraintType, - TaskDefinitionStatus: () => TaskDefinitionStatus, - TaskField: () => TaskField, - TaskFilesystemType: () => TaskFilesystemType, - TaskSetField: () => TaskSetField, - TaskSetNotFoundException: () => TaskSetNotFoundException, - TaskStopCode: () => TaskStopCode, - TransportProtocol: () => TransportProtocol, - UlimitName: () => UlimitName, - UnsupportedFeatureException: () => UnsupportedFeatureException, - UntagResourceCommand: () => UntagResourceCommand, - UpdateCapacityProviderCommand: () => UpdateCapacityProviderCommand, - UpdateClusterCommand: () => UpdateClusterCommand, - UpdateClusterSettingsCommand: () => UpdateClusterSettingsCommand, - UpdateContainerAgentCommand: () => UpdateContainerAgentCommand, - UpdateContainerInstancesStateCommand: () => UpdateContainerInstancesStateCommand, - UpdateInProgressException: () => UpdateInProgressException, - UpdateServiceCommand: () => UpdateServiceCommand, - UpdateServicePrimaryTaskSetCommand: () => UpdateServicePrimaryTaskSetCommand, - UpdateTaskProtectionCommand: () => UpdateTaskProtectionCommand, - UpdateTaskSetCommand: () => UpdateTaskSetCommand, - VersionConsistency: () => VersionConsistency, - __Client: () => import_smithy_client.Client, - paginateListAccountSettings: () => paginateListAccountSettings, - paginateListAttributes: () => paginateListAttributes, - paginateListClusters: () => paginateListClusters, - paginateListContainerInstances: () => paginateListContainerInstances, - paginateListServices: () => paginateListServices, - paginateListServicesByNamespace: () => paginateListServicesByNamespace, - paginateListTaskDefinitionFamilies: () => paginateListTaskDefinitionFamilies, - paginateListTaskDefinitions: () => paginateListTaskDefinitions, - paginateListTasks: () => paginateListTasks, - waitForServicesInactive: () => waitForServicesInactive, - waitForServicesStable: () => waitForServicesStable, - waitForTasksRunning: () => waitForTasksRunning, - waitForTasksStopped: () => waitForTasksStopped, - waitUntilServicesInactive: () => waitUntilServicesInactive, - waitUntilServicesStable: () => waitUntilServicesStable, - waitUntilTasksRunning: () => waitUntilTasksRunning, - waitUntilTasksStopped: () => waitUntilTasksStopped -}); -module.exports = __toCommonJS(index_exports); - -// src/ECSClient.ts -var import_middleware_host_header = __nccwpck_require__(25164); -var import_middleware_logger = __nccwpck_require__(65832); -var import_middleware_recursion_detection = __nccwpck_require__(39870); -var import_middleware_user_agent = __nccwpck_require__(70997); -var import_config_resolver = __nccwpck_require__(39316); -var import_core = __nccwpck_require__(22744); -var import_middleware_content_length = __nccwpck_require__(47212); -var import_middleware_endpoint = __nccwpck_require__(88205); -var import_middleware_retry = __nccwpck_require__(19618); -var import_httpAuthSchemeProvider = __nccwpck_require__(1367); +var middlewareHostHeader = __nccwpck_require__(25164); +var middlewareLogger = __nccwpck_require__(65832); +var middlewareRecursionDetection = __nccwpck_require__(39870); +var middlewareUserAgent = __nccwpck_require__(70997); +var configResolver = __nccwpck_require__(39316); +var core = __nccwpck_require__(22744); +var middlewareContentLength = __nccwpck_require__(47212); +var middlewareEndpoint = __nccwpck_require__(88205); +var middlewareRetry = __nccwpck_require__(19618); +var smithyClient = __nccwpck_require__(61411); +var httpAuthSchemeProvider = __nccwpck_require__(1367); +var runtimeConfig = __nccwpck_require__(41142); +var regionConfigResolver = __nccwpck_require__(26521); +var protocolHttp = __nccwpck_require__(13494); +var middlewareSerde = __nccwpck_require__(58305); +var core$1 = __nccwpck_require__(91446); +var uuid = __nccwpck_require__(90266); +var utilWaiter = __nccwpck_require__(95290); -// src/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "ecs" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "ecs", + }); }; - -// src/ECSClient.ts -var import_runtimeConfig = __nccwpck_require__(41142); - -// src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(26521); -var import_protocol_http = __nccwpck_require__(13494); -var import_smithy_client = __nccwpck_require__(61411); - -// src/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/ECSClient.ts -var ECSClient = class extends import_smithy_client.Client { - static { - __name(this, "ECSClient"); - } - /** - * The resolved configuration of ECSClient class. This is resolved and normalized from the {@link ECSClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultECSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; -// src/ECS.ts - - -// src/commands/CreateCapacityProviderCommand.ts - -var import_middleware_serde = __nccwpck_require__(58305); - - -// src/protocols/Aws_json1_1.ts -var import_core2 = __nccwpck_require__(91446); - - -var import_uuid = __nccwpck_require__(12048); - -// src/models/ECSServiceException.ts +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; -var ECSServiceException = class _ECSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "ECSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _ECSServiceException.prototype); - } +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); }; -// src/models/models_0.ts +class ECSClient extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); + const _config_4 = configResolver.resolveRegionConfig(_config_3); + const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); + const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); + const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultECSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} -var AccessDeniedException = class _AccessDeniedException extends ECSServiceException { - static { - __name(this, "AccessDeniedException"); - } - name = "AccessDeniedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - } +class ECSServiceException extends smithyClient.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, ECSServiceException.prototype); + } +} + +const AcceleratorManufacturer = { + AMAZON_WEB_SERVICES: "amazon-web-services", + AMD: "amd", + HABANA: "habana", + NVIDIA: "nvidia", + XILINX: "xilinx", +}; +const AcceleratorName = { + A100: "a100", + A10G: "a10g", + H100: "h100", + INFERENTIA: "inferentia", + K520: "k520", + K80: "k80", + M60: "m60", + RADEON_PRO_V520: "radeon-pro-v520", + T4: "t4", + T4G: "t4g", + V100: "v100", + VU9P: "vu9p", +}; +const AcceleratorType = { + FPGA: "fpga", + GPU: "gpu", + INFERENCE: "inference", +}; +class AccessDeniedException extends ECSServiceException { + name = "AccessDeniedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + } +} +const AgentUpdateStatus = { + FAILED: "FAILED", + PENDING: "PENDING", + STAGED: "STAGED", + STAGING: "STAGING", + UPDATED: "UPDATED", + UPDATING: "UPDATING", +}; +class ClientException extends ECSServiceException { + name = "ClientException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClientException.prototype); + } +} +class ClusterNotFoundException extends ECSServiceException { + name = "ClusterNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClusterNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClusterNotFoundException.prototype); + } +} +const ManagedDraining = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const ManagedScalingStatus = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const ManagedTerminationProtection = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const BareMetal = { + EXCLUDED: "excluded", + INCLUDED: "included", + REQUIRED: "required", +}; +const BurstablePerformance = { + EXCLUDED: "excluded", + INCLUDED: "included", + REQUIRED: "required", +}; +const CpuManufacturer = { + AMAZON_WEB_SERVICES: "amazon-web-services", + AMD: "amd", + INTEL: "intel", +}; +const InstanceGeneration = { + CURRENT: "current", + PREVIOUS: "previous", +}; +const LocalStorage = { + EXCLUDED: "excluded", + INCLUDED: "included", + REQUIRED: "required", +}; +const LocalStorageType = { + HDD: "hdd", + SSD: "ssd", +}; +const ManagedInstancesMonitoringOptions = { + BASIC: "BASIC", + DETAILED: "DETAILED", +}; +const PropagateMITags = { + CAPACITY_PROVIDER: "CAPACITY_PROVIDER", + NONE: "NONE", +}; +const CapacityProviderStatus = { + ACTIVE: "ACTIVE", + DEPROVISIONING: "DEPROVISIONING", + INACTIVE: "INACTIVE", + PROVISIONING: "PROVISIONING", +}; +const CapacityProviderType = { + EC2_AUTOSCALING: "EC2_AUTOSCALING", + FARGATE: "FARGATE", + FARGATE_SPOT: "FARGATE_SPOT", + MANAGED_INSTANCES: "MANAGED_INSTANCES", +}; +const CapacityProviderUpdateStatus = { + CREATE_COMPLETE: "CREATE_COMPLETE", + CREATE_FAILED: "CREATE_FAILED", + CREATE_IN_PROGRESS: "CREATE_IN_PROGRESS", + DELETE_COMPLETE: "DELETE_COMPLETE", + DELETE_FAILED: "DELETE_FAILED", + DELETE_IN_PROGRESS: "DELETE_IN_PROGRESS", + UPDATE_COMPLETE: "UPDATE_COMPLETE", + UPDATE_FAILED: "UPDATE_FAILED", + UPDATE_IN_PROGRESS: "UPDATE_IN_PROGRESS", +}; +class InvalidParameterException extends ECSServiceException { + name = "InvalidParameterException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidParameterException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidParameterException.prototype); + } +} +class LimitExceededException extends ECSServiceException { + name = "LimitExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "LimitExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, LimitExceededException.prototype); + } +} +class ServerException extends ECSServiceException { + name = "ServerException"; + $fault = "server"; + constructor(opts) { + super({ + name: "ServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, ServerException.prototype); + } +} +class UnsupportedFeatureException extends ECSServiceException { + name = "UnsupportedFeatureException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UnsupportedFeatureException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnsupportedFeatureException.prototype); + } +} +class UpdateInProgressException extends ECSServiceException { + name = "UpdateInProgressException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UpdateInProgressException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UpdateInProgressException.prototype); + } +} +const ExecuteCommandLogging = { + DEFAULT: "DEFAULT", + NONE: "NONE", + OVERRIDE: "OVERRIDE", }; -var AgentUpdateStatus = { - FAILED: "FAILED", - PENDING: "PENDING", - STAGED: "STAGED", - STAGING: "STAGING", - UPDATED: "UPDATED", - UPDATING: "UPDATING" +const ClusterSettingName = { + CONTAINER_INSIGHTS: "containerInsights", }; -var ClientException = class _ClientException extends ECSServiceException { - static { - __name(this, "ClientException"); - } - name = "ClientException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ClientException.prototype); - } +class NamespaceNotFoundException extends ECSServiceException { + name = "NamespaceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "NamespaceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, NamespaceNotFoundException.prototype); + } +} +const AvailabilityZoneRebalancing = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const DeploymentLifecycleHookStage = { + POST_PRODUCTION_TRAFFIC_SHIFT: "POST_PRODUCTION_TRAFFIC_SHIFT", + POST_SCALE_UP: "POST_SCALE_UP", + POST_TEST_TRAFFIC_SHIFT: "POST_TEST_TRAFFIC_SHIFT", + PRE_SCALE_UP: "PRE_SCALE_UP", + PRODUCTION_TRAFFIC_SHIFT: "PRODUCTION_TRAFFIC_SHIFT", + RECONCILE_SERVICE: "RECONCILE_SERVICE", + TEST_TRAFFIC_SHIFT: "TEST_TRAFFIC_SHIFT", +}; +const DeploymentStrategy = { + BLUE_GREEN: "BLUE_GREEN", + ROLLING: "ROLLING", +}; +const DeploymentControllerType = { + CODE_DEPLOY: "CODE_DEPLOY", + ECS: "ECS", + EXTERNAL: "EXTERNAL", +}; +const LaunchType = { + EC2: "EC2", + EXTERNAL: "EXTERNAL", + FARGATE: "FARGATE", + MANAGED_INSTANCES: "MANAGED_INSTANCES", +}; +const AssignPublicIp = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const PlacementConstraintType = { + DISTINCT_INSTANCE: "distinctInstance", + MEMBER_OF: "memberOf", +}; +const PlacementStrategyType = { + BINPACK: "binpack", + RANDOM: "random", + SPREAD: "spread", +}; +const PropagateTags = { + NONE: "NONE", + SERVICE: "SERVICE", + TASK_DEFINITION: "TASK_DEFINITION", +}; +const SchedulingStrategy = { + DAEMON: "DAEMON", + REPLICA: "REPLICA", +}; +const LogDriver = { + AWSFIRELENS: "awsfirelens", + AWSLOGS: "awslogs", + FLUENTD: "fluentd", + GELF: "gelf", + JOURNALD: "journald", + JSON_FILE: "json-file", + SPLUNK: "splunk", + SYSLOG: "syslog", +}; +const TaskFilesystemType = { + EXT3: "ext3", + EXT4: "ext4", + NTFS: "ntfs", + XFS: "xfs", +}; +const EBSResourceType = { + VOLUME: "volume", +}; +const DeploymentRolloutState = { + COMPLETED: "COMPLETED", + FAILED: "FAILED", + IN_PROGRESS: "IN_PROGRESS", +}; +const ScaleUnit = { + PERCENT: "PERCENT", +}; +const StabilityStatus = { + STABILIZING: "STABILIZING", + STEADY_STATE: "STEADY_STATE", +}; +class PlatformTaskDefinitionIncompatibilityException extends ECSServiceException { + name = "PlatformTaskDefinitionIncompatibilityException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PlatformTaskDefinitionIncompatibilityException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PlatformTaskDefinitionIncompatibilityException.prototype); + } +} +class PlatformUnknownException extends ECSServiceException { + name = "PlatformUnknownException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PlatformUnknownException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PlatformUnknownException.prototype); + } +} +class ServiceNotActiveException extends ECSServiceException { + name = "ServiceNotActiveException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceNotActiveException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceNotActiveException.prototype); + } +} +class ServiceNotFoundException extends ECSServiceException { + name = "ServiceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceNotFoundException.prototype); + } +} +const SettingName = { + AWSVPC_TRUNKING: "awsvpcTrunking", + CONTAINER_INSIGHTS: "containerInsights", + CONTAINER_INSTANCE_LONG_ARN_FORMAT: "containerInstanceLongArnFormat", + DEFAULT_LOG_DRIVER_MODE: "defaultLogDriverMode", + FARGATE_FIPS_MODE: "fargateFIPSMode", + FARGATE_TASK_RETIREMENT_WAIT_PERIOD: "fargateTaskRetirementWaitPeriod", + GUARD_DUTY_ACTIVATE: "guardDutyActivate", + SERVICE_LONG_ARN_FORMAT: "serviceLongArnFormat", + TAG_RESOURCE_AUTHORIZATION: "tagResourceAuthorization", + TASK_LONG_ARN_FORMAT: "taskLongArnFormat", +}; +const SettingType = { + AWS_MANAGED: "aws_managed", + USER: "user", +}; +const TargetType = { + CONTAINER_INSTANCE: "container-instance", +}; +class TargetNotFoundException extends ECSServiceException { + name = "TargetNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TargetNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TargetNotFoundException.prototype); + } +} +class ClusterContainsCapacityProviderException extends ECSServiceException { + name = "ClusterContainsCapacityProviderException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClusterContainsCapacityProviderException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClusterContainsCapacityProviderException.prototype); + } +} +class ClusterContainsContainerInstancesException extends ECSServiceException { + name = "ClusterContainsContainerInstancesException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClusterContainsContainerInstancesException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClusterContainsContainerInstancesException.prototype); + } +} +class ClusterContainsServicesException extends ECSServiceException { + name = "ClusterContainsServicesException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClusterContainsServicesException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClusterContainsServicesException.prototype); + } +} +class ClusterContainsTasksException extends ECSServiceException { + name = "ClusterContainsTasksException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ClusterContainsTasksException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ClusterContainsTasksException.prototype); + } +} +const Compatibility = { + EC2: "EC2", + EXTERNAL: "EXTERNAL", + FARGATE: "FARGATE", + MANAGED_INSTANCES: "MANAGED_INSTANCES", +}; +const ContainerCondition = { + COMPLETE: "COMPLETE", + HEALTHY: "HEALTHY", + START: "START", + SUCCESS: "SUCCESS", +}; +const EnvironmentFileType = { + S3: "s3", +}; +const FirelensConfigurationType = { + FLUENTBIT: "fluentbit", + FLUENTD: "fluentd", +}; +const DeviceCgroupPermission = { + MKNOD: "mknod", + READ: "read", + WRITE: "write", +}; +const ApplicationProtocol = { + GRPC: "grpc", + HTTP: "http", + HTTP2: "http2", +}; +const TransportProtocol = { + TCP: "tcp", + UDP: "udp", +}; +const ResourceType = { + GPU: "GPU", + INFERENCE_ACCELERATOR: "InferenceAccelerator", +}; +const UlimitName = { + CORE: "core", + CPU: "cpu", + DATA: "data", + FSIZE: "fsize", + LOCKS: "locks", + MEMLOCK: "memlock", + MSGQUEUE: "msgqueue", + NICE: "nice", + NOFILE: "nofile", + NPROC: "nproc", + RSS: "rss", + RTPRIO: "rtprio", + RTTIME: "rttime", + SIGPENDING: "sigpending", + STACK: "stack", +}; +const VersionConsistency = { + DISABLED: "disabled", + ENABLED: "enabled", +}; +const IpcMode = { + HOST: "host", + NONE: "none", + TASK: "task", +}; +const NetworkMode = { + AWSVPC: "awsvpc", + BRIDGE: "bridge", + HOST: "host", + NONE: "none", +}; +const PidMode = { + HOST: "host", + TASK: "task", +}; +const TaskDefinitionPlacementConstraintType = { + MEMBER_OF: "memberOf", +}; +const ProxyConfigurationType = { + APPMESH: "APPMESH", +}; +const CPUArchitecture = { + ARM64: "ARM64", + X86_64: "X86_64", +}; +const OSFamily = { + LINUX: "LINUX", + WINDOWS_SERVER_2004_CORE: "WINDOWS_SERVER_2004_CORE", + WINDOWS_SERVER_2016_FULL: "WINDOWS_SERVER_2016_FULL", + WINDOWS_SERVER_2019_CORE: "WINDOWS_SERVER_2019_CORE", + WINDOWS_SERVER_2019_FULL: "WINDOWS_SERVER_2019_FULL", + WINDOWS_SERVER_2022_CORE: "WINDOWS_SERVER_2022_CORE", + WINDOWS_SERVER_2022_FULL: "WINDOWS_SERVER_2022_FULL", + WINDOWS_SERVER_2025_CORE: "WINDOWS_SERVER_2025_CORE", + WINDOWS_SERVER_2025_FULL: "WINDOWS_SERVER_2025_FULL", + WINDOWS_SERVER_20H2_CORE: "WINDOWS_SERVER_20H2_CORE", +}; +const TaskDefinitionStatus = { + ACTIVE: "ACTIVE", + DELETE_IN_PROGRESS: "DELETE_IN_PROGRESS", + INACTIVE: "INACTIVE", +}; +const Scope = { + SHARED: "shared", + TASK: "task", +}; +const EFSAuthorizationConfigIAM = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +const EFSTransitEncryption = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", +}; +class TaskSetNotFoundException extends ECSServiceException { + name = "TaskSetNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TaskSetNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TaskSetNotFoundException.prototype); + } +} +const InstanceHealthCheckState = { + IMPAIRED: "IMPAIRED", + INITIALIZING: "INITIALIZING", + INSUFFICIENT_DATA: "INSUFFICIENT_DATA", + OK: "OK", +}; +const InstanceHealthCheckType = { + CONTAINER_RUNTIME: "CONTAINER_RUNTIME", +}; +const CapacityProviderField = { + TAGS: "TAGS", +}; +const ClusterField = { + ATTACHMENTS: "ATTACHMENTS", + CONFIGURATIONS: "CONFIGURATIONS", + SETTINGS: "SETTINGS", + STATISTICS: "STATISTICS", + TAGS: "TAGS", +}; +const ContainerInstanceField = { + CONTAINER_INSTANCE_HEALTH: "CONTAINER_INSTANCE_HEALTH", + TAGS: "TAGS", +}; +const ServiceDeploymentRollbackMonitorsStatus = { + DISABLED: "DISABLED", + MONITORING: "MONITORING", + MONITORING_COMPLETE: "MONITORING_COMPLETE", + TRIGGERED: "TRIGGERED", +}; +const ServiceDeploymentLifecycleStage = { + BAKE_TIME: "BAKE_TIME", + CLEAN_UP: "CLEAN_UP", + POST_PRODUCTION_TRAFFIC_SHIFT: "POST_PRODUCTION_TRAFFIC_SHIFT", + POST_SCALE_UP: "POST_SCALE_UP", + POST_TEST_TRAFFIC_SHIFT: "POST_TEST_TRAFFIC_SHIFT", + PRE_SCALE_UP: "PRE_SCALE_UP", + PRODUCTION_TRAFFIC_SHIFT: "PRODUCTION_TRAFFIC_SHIFT", + RECONCILE_SERVICE: "RECONCILE_SERVICE", + SCALE_UP: "SCALE_UP", + TEST_TRAFFIC_SHIFT: "TEST_TRAFFIC_SHIFT", +}; +const ServiceDeploymentStatus = { + IN_PROGRESS: "IN_PROGRESS", + PENDING: "PENDING", + ROLLBACK_FAILED: "ROLLBACK_FAILED", + ROLLBACK_IN_PROGRESS: "ROLLBACK_IN_PROGRESS", + ROLLBACK_REQUESTED: "ROLLBACK_REQUESTED", + ROLLBACK_SUCCESSFUL: "ROLLBACK_SUCCESSFUL", + STOPPED: "STOPPED", + STOP_REQUESTED: "STOP_REQUESTED", + SUCCESSFUL: "SUCCESSFUL", +}; +const ServiceField = { + TAGS: "TAGS", +}; +const TaskDefinitionField = { + TAGS: "TAGS", +}; +const TaskField = { + TAGS: "TAGS", +}; +const Connectivity = { + CONNECTED: "CONNECTED", + DISCONNECTED: "DISCONNECTED", +}; +const HealthStatus = { + HEALTHY: "HEALTHY", + UNHEALTHY: "UNHEALTHY", + UNKNOWN: "UNKNOWN", +}; +const ManagedAgentName = { + ExecuteCommandAgent: "ExecuteCommandAgent", +}; +const TaskStopCode = { + ESSENTIAL_CONTAINER_EXITED: "EssentialContainerExited", + SERVICE_SCHEDULER_INITIATED: "ServiceSchedulerInitiated", + SPOT_INTERRUPTION: "SpotInterruption", + TASK_FAILED_TO_START: "TaskFailedToStart", + TERMINATION_NOTICE: "TerminationNotice", + USER_INITIATED: "UserInitiated", +}; +const TaskSetField = { + TAGS: "TAGS", +}; +class TargetNotConnectedException extends ECSServiceException { + name = "TargetNotConnectedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TargetNotConnectedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TargetNotConnectedException.prototype); + } +} +class ResourceNotFoundException extends ECSServiceException { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +} +const ContainerInstanceStatus = { + ACTIVE: "ACTIVE", + DEREGISTERING: "DEREGISTERING", + DRAINING: "DRAINING", + REGISTERING: "REGISTERING", + REGISTRATION_FAILED: "REGISTRATION_FAILED", }; -var ManagedDraining = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" +const TaskDefinitionFamilyStatus = { + ACTIVE: "ACTIVE", + ALL: "ALL", + INACTIVE: "INACTIVE", }; -var ManagedScalingStatus = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" +const SortOrder = { + ASC: "ASC", + DESC: "DESC", }; -var ManagedTerminationProtection = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" +const DesiredStatus = { + PENDING: "PENDING", + RUNNING: "RUNNING", + STOPPED: "STOPPED", }; -var CapacityProviderStatus = { - ACTIVE: "ACTIVE", - INACTIVE: "INACTIVE" +const SessionFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.tokenValue && { tokenValue: smithyClient.SENSITIVE_STRING }), +}); +const ExecuteCommandResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...(obj.session && { session: SessionFilterSensitiveLog(obj.session) }), +}); + +class AttributeLimitExceededException extends ECSServiceException { + name = "AttributeLimitExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "AttributeLimitExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AttributeLimitExceededException.prototype); + } +} +class ResourceInUseException extends ECSServiceException { + name = "ResourceInUseException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceInUseException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceInUseException.prototype); + } +} +const PlatformDeviceType = { + GPU: "GPU", }; -var CapacityProviderUpdateStatus = { - DELETE_COMPLETE: "DELETE_COMPLETE", - DELETE_FAILED: "DELETE_FAILED", - DELETE_IN_PROGRESS: "DELETE_IN_PROGRESS", - UPDATE_COMPLETE: "UPDATE_COMPLETE", - UPDATE_FAILED: "UPDATE_FAILED", - UPDATE_IN_PROGRESS: "UPDATE_IN_PROGRESS" +class BlockedException extends ECSServiceException { + name = "BlockedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "BlockedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, BlockedException.prototype); + } +} +class ConflictException extends ECSServiceException { + name = "ConflictException"; + $fault = "client"; + resourceIds; + constructor(opts) { + super({ + name: "ConflictException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ConflictException.prototype); + this.resourceIds = opts.resourceIds; + } +} +class ServiceDeploymentNotFoundException extends ECSServiceException { + name = "ServiceDeploymentNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceDeploymentNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceDeploymentNotFoundException.prototype); + } +} +const StopServiceDeploymentStopType = { + ABORT: "ABORT", + ROLLBACK: "ROLLBACK", }; -var InvalidParameterException = class _InvalidParameterException extends ECSServiceException { - static { - __name(this, "InvalidParameterException"); - } - name = "InvalidParameterException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidParameterException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidParameterException.prototype); - } +class MissingVersionException extends ECSServiceException { + name = "MissingVersionException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MissingVersionException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, MissingVersionException.prototype); + } +} +class NoUpdateAvailableException extends ECSServiceException { + name = "NoUpdateAvailableException"; + $fault = "client"; + constructor(opts) { + super({ + name: "NoUpdateAvailableException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, NoUpdateAvailableException.prototype); + } +} + +const se_CreateCapacityProviderCommand = async (input, context) => { + const headers = sharedHeaders("CreateCapacityProvider"); + let body; + body = JSON.stringify(se_CreateCapacityProviderRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_CreateClusterCommand = async (input, context) => { + const headers = sharedHeaders("CreateCluster"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_CreateServiceCommand = async (input, context) => { + const headers = sharedHeaders("CreateService"); + let body; + body = JSON.stringify(se_CreateServiceRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_CreateTaskSetCommand = async (input, context) => { + const headers = sharedHeaders("CreateTaskSet"); + let body; + body = JSON.stringify(se_CreateTaskSetRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteAccountSettingCommand = async (input, context) => { + const headers = sharedHeaders("DeleteAccountSetting"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteAttributesCommand = async (input, context) => { + const headers = sharedHeaders("DeleteAttributes"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteCapacityProviderCommand = async (input, context) => { + const headers = sharedHeaders("DeleteCapacityProvider"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteClusterCommand = async (input, context) => { + const headers = sharedHeaders("DeleteCluster"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteServiceCommand = async (input, context) => { + const headers = sharedHeaders("DeleteService"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteTaskDefinitionsCommand = async (input, context) => { + const headers = sharedHeaders("DeleteTaskDefinitions"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeleteTaskSetCommand = async (input, context) => { + const headers = sharedHeaders("DeleteTaskSet"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeregisterContainerInstanceCommand = async (input, context) => { + const headers = sharedHeaders("DeregisterContainerInstance"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DeregisterTaskDefinitionCommand = async (input, context) => { + const headers = sharedHeaders("DeregisterTaskDefinition"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeCapacityProvidersCommand = async (input, context) => { + const headers = sharedHeaders("DescribeCapacityProviders"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeClustersCommand = async (input, context) => { + const headers = sharedHeaders("DescribeClusters"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeContainerInstancesCommand = async (input, context) => { + const headers = sharedHeaders("DescribeContainerInstances"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeServiceDeploymentsCommand = async (input, context) => { + const headers = sharedHeaders("DescribeServiceDeployments"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeServiceRevisionsCommand = async (input, context) => { + const headers = sharedHeaders("DescribeServiceRevisions"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeServicesCommand = async (input, context) => { + const headers = sharedHeaders("DescribeServices"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeTaskDefinitionCommand = async (input, context) => { + const headers = sharedHeaders("DescribeTaskDefinition"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeTasksCommand = async (input, context) => { + const headers = sharedHeaders("DescribeTasks"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DescribeTaskSetsCommand = async (input, context) => { + const headers = sharedHeaders("DescribeTaskSets"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_DiscoverPollEndpointCommand = async (input, context) => { + const headers = sharedHeaders("DiscoverPollEndpoint"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ExecuteCommandCommand = async (input, context) => { + const headers = sharedHeaders("ExecuteCommand"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_GetTaskProtectionCommand = async (input, context) => { + const headers = sharedHeaders("GetTaskProtection"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListAccountSettingsCommand = async (input, context) => { + const headers = sharedHeaders("ListAccountSettings"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListAttributesCommand = async (input, context) => { + const headers = sharedHeaders("ListAttributes"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListClustersCommand = async (input, context) => { + const headers = sharedHeaders("ListClusters"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListContainerInstancesCommand = async (input, context) => { + const headers = sharedHeaders("ListContainerInstances"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListServiceDeploymentsCommand = async (input, context) => { + const headers = sharedHeaders("ListServiceDeployments"); + let body; + body = JSON.stringify(se_ListServiceDeploymentsRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListServicesCommand = async (input, context) => { + const headers = sharedHeaders("ListServices"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListServicesByNamespaceCommand = async (input, context) => { + const headers = sharedHeaders("ListServicesByNamespace"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListTagsForResourceCommand = async (input, context) => { + const headers = sharedHeaders("ListTagsForResource"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListTaskDefinitionFamiliesCommand = async (input, context) => { + const headers = sharedHeaders("ListTaskDefinitionFamilies"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListTaskDefinitionsCommand = async (input, context) => { + const headers = sharedHeaders("ListTaskDefinitions"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_ListTasksCommand = async (input, context) => { + const headers = sharedHeaders("ListTasks"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_PutAccountSettingCommand = async (input, context) => { + const headers = sharedHeaders("PutAccountSetting"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_PutAccountSettingDefaultCommand = async (input, context) => { + const headers = sharedHeaders("PutAccountSettingDefault"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_PutAttributesCommand = async (input, context) => { + const headers = sharedHeaders("PutAttributes"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_PutClusterCapacityProvidersCommand = async (input, context) => { + const headers = sharedHeaders("PutClusterCapacityProviders"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_RegisterContainerInstanceCommand = async (input, context) => { + const headers = sharedHeaders("RegisterContainerInstance"); + let body; + body = JSON.stringify(se_RegisterContainerInstanceRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_RegisterTaskDefinitionCommand = async (input, context) => { + const headers = sharedHeaders("RegisterTaskDefinition"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_RunTaskCommand = async (input, context) => { + const headers = sharedHeaders("RunTask"); + let body; + body = JSON.stringify(se_RunTaskRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_StartTaskCommand = async (input, context) => { + const headers = sharedHeaders("StartTask"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_StopServiceDeploymentCommand = async (input, context) => { + const headers = sharedHeaders("StopServiceDeployment"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_StopTaskCommand = async (input, context) => { + const headers = sharedHeaders("StopTask"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_SubmitAttachmentStateChangesCommand = async (input, context) => { + const headers = sharedHeaders("SubmitAttachmentStateChanges"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_SubmitContainerStateChangeCommand = async (input, context) => { + const headers = sharedHeaders("SubmitContainerStateChange"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_SubmitTaskStateChangeCommand = async (input, context) => { + const headers = sharedHeaders("SubmitTaskStateChange"); + let body; + body = JSON.stringify(se_SubmitTaskStateChangeRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_TagResourceCommand = async (input, context) => { + const headers = sharedHeaders("TagResource"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UntagResourceCommand = async (input, context) => { + const headers = sharedHeaders("UntagResource"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateCapacityProviderCommand = async (input, context) => { + const headers = sharedHeaders("UpdateCapacityProvider"); + let body; + body = JSON.stringify(se_UpdateCapacityProviderRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateClusterCommand = async (input, context) => { + const headers = sharedHeaders("UpdateCluster"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateClusterSettingsCommand = async (input, context) => { + const headers = sharedHeaders("UpdateClusterSettings"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateContainerAgentCommand = async (input, context) => { + const headers = sharedHeaders("UpdateContainerAgent"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateContainerInstancesStateCommand = async (input, context) => { + const headers = sharedHeaders("UpdateContainerInstancesState"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateServiceCommand = async (input, context) => { + const headers = sharedHeaders("UpdateService"); + let body; + body = JSON.stringify(se_UpdateServiceRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateServicePrimaryTaskSetCommand = async (input, context) => { + const headers = sharedHeaders("UpdateServicePrimaryTaskSet"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateTaskProtectionCommand = async (input, context) => { + const headers = sharedHeaders("UpdateTaskProtection"); + let body; + body = JSON.stringify(smithyClient._json(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const se_UpdateTaskSetCommand = async (input, context) => { + const headers = sharedHeaders("UpdateTaskSet"); + let body; + body = JSON.stringify(se_UpdateTaskSetRequest(input)); + return buildHttpRpcRequest(context, headers, "/", undefined, body); +}; +const de_CreateCapacityProviderCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_CreateCapacityProviderResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var LimitExceededException = class _LimitExceededException extends ECSServiceException { - static { - __name(this, "LimitExceededException"); - } - name = "LimitExceededException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "LimitExceededException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _LimitExceededException.prototype); - } +const de_CreateClusterCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ServerException = class _ServerException extends ECSServiceException { - static { - __name(this, "ServerException"); - } - name = "ServerException"; - $fault = "server"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _ServerException.prototype); - } +const de_CreateServiceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_CreateServiceResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var UpdateInProgressException = class _UpdateInProgressException extends ECSServiceException { - static { - __name(this, "UpdateInProgressException"); - } - name = "UpdateInProgressException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UpdateInProgressException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UpdateInProgressException.prototype); - } +const de_CreateTaskSetCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_CreateTaskSetResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ExecuteCommandLogging = { - DEFAULT: "DEFAULT", - NONE: "NONE", - OVERRIDE: "OVERRIDE" +const de_DeleteAccountSettingCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ClusterSettingName = { - CONTAINER_INSIGHTS: "containerInsights" +const de_DeleteAttributesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var NamespaceNotFoundException = class _NamespaceNotFoundException extends ECSServiceException { - static { - __name(this, "NamespaceNotFoundException"); - } - name = "NamespaceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "NamespaceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NamespaceNotFoundException.prototype); - } +const de_DeleteCapacityProviderCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeleteCapacityProviderResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ClusterNotFoundException = class _ClusterNotFoundException extends ECSServiceException { - static { - __name(this, "ClusterNotFoundException"); - } - name = "ClusterNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ClusterNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ClusterNotFoundException.prototype); - } +const de_DeleteClusterCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var AvailabilityZoneRebalancing = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" +const de_DeleteServiceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeleteServiceResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var DeploymentLifecycleHookStage = { - POST_PRODUCTION_TRAFFIC_SHIFT: "POST_PRODUCTION_TRAFFIC_SHIFT", - POST_SCALE_UP: "POST_SCALE_UP", - POST_TEST_TRAFFIC_SHIFT: "POST_TEST_TRAFFIC_SHIFT", - PRE_SCALE_UP: "PRE_SCALE_UP", - PRODUCTION_TRAFFIC_SHIFT: "PRODUCTION_TRAFFIC_SHIFT", - RECONCILE_SERVICE: "RECONCILE_SERVICE", - TEST_TRAFFIC_SHIFT: "TEST_TRAFFIC_SHIFT" +const de_DeleteTaskDefinitionsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeleteTaskDefinitionsResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var DeploymentStrategy = { - BLUE_GREEN: "BLUE_GREEN", - ROLLING: "ROLLING" +const de_DeleteTaskSetCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeleteTaskSetResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var DeploymentControllerType = { - CODE_DEPLOY: "CODE_DEPLOY", - ECS: "ECS", - EXTERNAL: "EXTERNAL" -}; -var LaunchType = { - EC2: "EC2", - EXTERNAL: "EXTERNAL", - FARGATE: "FARGATE" -}; -var AssignPublicIp = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" -}; -var PlacementConstraintType = { - DISTINCT_INSTANCE: "distinctInstance", - MEMBER_OF: "memberOf" -}; -var PlacementStrategyType = { - BINPACK: "binpack", - RANDOM: "random", - SPREAD: "spread" -}; -var PropagateTags = { - NONE: "NONE", - SERVICE: "SERVICE", - TASK_DEFINITION: "TASK_DEFINITION" -}; -var SchedulingStrategy = { - DAEMON: "DAEMON", - REPLICA: "REPLICA" -}; -var LogDriver = { - AWSFIRELENS: "awsfirelens", - AWSLOGS: "awslogs", - FLUENTD: "fluentd", - GELF: "gelf", - JOURNALD: "journald", - JSON_FILE: "json-file", - SPLUNK: "splunk", - SYSLOG: "syslog" -}; -var TaskFilesystemType = { - EXT3: "ext3", - EXT4: "ext4", - NTFS: "ntfs", - XFS: "xfs" -}; -var EBSResourceType = { - VOLUME: "volume" -}; -var DeploymentRolloutState = { - COMPLETED: "COMPLETED", - FAILED: "FAILED", - IN_PROGRESS: "IN_PROGRESS" -}; -var ScaleUnit = { - PERCENT: "PERCENT" -}; -var StabilityStatus = { - STABILIZING: "STABILIZING", - STEADY_STATE: "STEADY_STATE" -}; -var PlatformTaskDefinitionIncompatibilityException = class _PlatformTaskDefinitionIncompatibilityException extends ECSServiceException { - static { - __name(this, "PlatformTaskDefinitionIncompatibilityException"); - } - name = "PlatformTaskDefinitionIncompatibilityException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PlatformTaskDefinitionIncompatibilityException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PlatformTaskDefinitionIncompatibilityException.prototype); - } +const de_DeregisterContainerInstanceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeregisterContainerInstanceResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var PlatformUnknownException = class _PlatformUnknownException extends ECSServiceException { - static { - __name(this, "PlatformUnknownException"); - } - name = "PlatformUnknownException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PlatformUnknownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PlatformUnknownException.prototype); - } +const de_DeregisterTaskDefinitionCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DeregisterTaskDefinitionResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var UnsupportedFeatureException = class _UnsupportedFeatureException extends ECSServiceException { - static { - __name(this, "UnsupportedFeatureException"); - } - name = "UnsupportedFeatureException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnsupportedFeatureException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedFeatureException.prototype); - } +const de_DescribeCapacityProvidersCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeCapacityProvidersResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ServiceNotActiveException = class _ServiceNotActiveException extends ECSServiceException { - static { - __name(this, "ServiceNotActiveException"); - } - name = "ServiceNotActiveException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ServiceNotActiveException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ServiceNotActiveException.prototype); - } +const de_DescribeClustersCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var ServiceNotFoundException = class _ServiceNotFoundException extends ECSServiceException { - static { - __name(this, "ServiceNotFoundException"); - } - name = "ServiceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ServiceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ServiceNotFoundException.prototype); - } +const de_DescribeContainerInstancesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeContainerInstancesResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var SettingName = { - AWSVPC_TRUNKING: "awsvpcTrunking", - CONTAINER_INSIGHTS: "containerInsights", - CONTAINER_INSTANCE_LONG_ARN_FORMAT: "containerInstanceLongArnFormat", - DEFAULT_LOG_DRIVER_MODE: "defaultLogDriverMode", - FARGATE_FIPS_MODE: "fargateFIPSMode", - FARGATE_TASK_RETIREMENT_WAIT_PERIOD: "fargateTaskRetirementWaitPeriod", - GUARD_DUTY_ACTIVATE: "guardDutyActivate", - SERVICE_LONG_ARN_FORMAT: "serviceLongArnFormat", - TAG_RESOURCE_AUTHORIZATION: "tagResourceAuthorization", - TASK_LONG_ARN_FORMAT: "taskLongArnFormat" +const de_DescribeServiceDeploymentsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeServiceDeploymentsResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var SettingType = { - AWS_MANAGED: "aws_managed", - USER: "user" +const de_DescribeServiceRevisionsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeServiceRevisionsResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var TargetType = { - CONTAINER_INSTANCE: "container-instance" +const de_DescribeServicesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeServicesResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; }; -var TargetNotFoundException = class _TargetNotFoundException extends ECSServiceException { - static { - __name(this, "TargetNotFoundException"); - } - name = "TargetNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TargetNotFoundException", - $fault: "client", - ...opts +const de_DescribeTaskDefinitionCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeTaskDefinitionResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_DescribeTasksCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeTasksResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_DescribeTaskSetsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_DescribeTaskSetsResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_DiscoverPollEndpointCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ExecuteCommandCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_GetTaskProtectionCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_GetTaskProtectionResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListAccountSettingsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListAttributesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListClustersCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListContainerInstancesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListServiceDeploymentsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_ListServiceDeploymentsResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListServicesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListServicesByNamespaceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListTagsForResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListTaskDefinitionFamiliesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListTaskDefinitionsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_ListTasksCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_PutAccountSettingCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_PutAccountSettingDefaultCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_PutAttributesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_PutClusterCapacityProvidersCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_RegisterContainerInstanceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_RegisterContainerInstanceResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_RegisterTaskDefinitionCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_RegisterTaskDefinitionResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_RunTaskCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_RunTaskResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_StartTaskCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_StartTaskResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_StopServiceDeploymentCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_StopTaskCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_StopTaskResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_SubmitAttachmentStateChangesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_SubmitContainerStateChangeCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_SubmitTaskStateChangeCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_TagResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UntagResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateCapacityProviderCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateCapacityProviderResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateClusterCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateClusterSettingsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = smithyClient._json(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateContainerAgentCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateContainerAgentResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateContainerInstancesStateCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateContainerInstancesStateResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateServiceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateServiceResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateServicePrimaryTaskSetCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateServicePrimaryTaskSetResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateTaskProtectionCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateTaskProtectionResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_UpdateTaskSetCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await core$1.parseJsonBody(output.body, context); + let contents = {}; + contents = de_UpdateTaskSetResponse(data); + const response = { + $metadata: deserializeMetadata(output), + ...contents, + }; + return response; +}; +const de_CommandError = async (output, context) => { + const parsedOutput = { + ...output, + body: await core$1.parseJsonErrorBody(output.body, context), + }; + const errorCode = core$1.loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "ClientException": + case "com.amazonaws.ecs#ClientException": + throw await de_ClientExceptionRes(parsedOutput); + case "ClusterNotFoundException": + case "com.amazonaws.ecs#ClusterNotFoundException": + throw await de_ClusterNotFoundExceptionRes(parsedOutput); + case "InvalidParameterException": + case "com.amazonaws.ecs#InvalidParameterException": + throw await de_InvalidParameterExceptionRes(parsedOutput); + case "LimitExceededException": + case "com.amazonaws.ecs#LimitExceededException": + throw await de_LimitExceededExceptionRes(parsedOutput); + case "ServerException": + case "com.amazonaws.ecs#ServerException": + throw await de_ServerExceptionRes(parsedOutput); + case "UnsupportedFeatureException": + case "com.amazonaws.ecs#UnsupportedFeatureException": + throw await de_UnsupportedFeatureExceptionRes(parsedOutput); + case "UpdateInProgressException": + case "com.amazonaws.ecs#UpdateInProgressException": + throw await de_UpdateInProgressExceptionRes(parsedOutput); + case "NamespaceNotFoundException": + case "com.amazonaws.ecs#NamespaceNotFoundException": + throw await de_NamespaceNotFoundExceptionRes(parsedOutput); + case "AccessDeniedException": + case "com.amazonaws.ecs#AccessDeniedException": + throw await de_AccessDeniedExceptionRes(parsedOutput); + case "PlatformTaskDefinitionIncompatibilityException": + case "com.amazonaws.ecs#PlatformTaskDefinitionIncompatibilityException": + throw await de_PlatformTaskDefinitionIncompatibilityExceptionRes(parsedOutput); + case "PlatformUnknownException": + case "com.amazonaws.ecs#PlatformUnknownException": + throw await de_PlatformUnknownExceptionRes(parsedOutput); + case "ServiceNotActiveException": + case "com.amazonaws.ecs#ServiceNotActiveException": + throw await de_ServiceNotActiveExceptionRes(parsedOutput); + case "ServiceNotFoundException": + case "com.amazonaws.ecs#ServiceNotFoundException": + throw await de_ServiceNotFoundExceptionRes(parsedOutput); + case "TargetNotFoundException": + case "com.amazonaws.ecs#TargetNotFoundException": + throw await de_TargetNotFoundExceptionRes(parsedOutput); + case "ClusterContainsCapacityProviderException": + case "com.amazonaws.ecs#ClusterContainsCapacityProviderException": + throw await de_ClusterContainsCapacityProviderExceptionRes(parsedOutput); + case "ClusterContainsContainerInstancesException": + case "com.amazonaws.ecs#ClusterContainsContainerInstancesException": + throw await de_ClusterContainsContainerInstancesExceptionRes(parsedOutput); + case "ClusterContainsServicesException": + case "com.amazonaws.ecs#ClusterContainsServicesException": + throw await de_ClusterContainsServicesExceptionRes(parsedOutput); + case "ClusterContainsTasksException": + case "com.amazonaws.ecs#ClusterContainsTasksException": + throw await de_ClusterContainsTasksExceptionRes(parsedOutput); + case "TaskSetNotFoundException": + case "com.amazonaws.ecs#TaskSetNotFoundException": + throw await de_TaskSetNotFoundExceptionRes(parsedOutput); + case "TargetNotConnectedException": + case "com.amazonaws.ecs#TargetNotConnectedException": + throw await de_TargetNotConnectedExceptionRes(parsedOutput); + case "ResourceNotFoundException": + case "com.amazonaws.ecs#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput); + case "AttributeLimitExceededException": + case "com.amazonaws.ecs#AttributeLimitExceededException": + throw await de_AttributeLimitExceededExceptionRes(parsedOutput); + case "ResourceInUseException": + case "com.amazonaws.ecs#ResourceInUseException": + throw await de_ResourceInUseExceptionRes(parsedOutput); + case "BlockedException": + case "com.amazonaws.ecs#BlockedException": + throw await de_BlockedExceptionRes(parsedOutput); + case "ConflictException": + case "com.amazonaws.ecs#ConflictException": + throw await de_ConflictExceptionRes(parsedOutput); + case "ServiceDeploymentNotFoundException": + case "com.amazonaws.ecs#ServiceDeploymentNotFoundException": + throw await de_ServiceDeploymentNotFoundExceptionRes(parsedOutput); + case "MissingVersionException": + case "com.amazonaws.ecs#MissingVersionException": + throw await de_MissingVersionExceptionRes(parsedOutput); + case "NoUpdateAvailableException": + case "com.amazonaws.ecs#NoUpdateAvailableException": + throw await de_NoUpdateAvailableExceptionRes(parsedOutput); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode, + }); + } +}; +const de_AccessDeniedExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_AttributeLimitExceededExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new AttributeLimitExceededException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_BlockedExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new BlockedException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClientExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClusterContainsCapacityProviderExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClusterContainsCapacityProviderException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClusterContainsContainerInstancesExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClusterContainsContainerInstancesException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClusterContainsServicesExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClusterContainsServicesException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClusterContainsTasksExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClusterContainsTasksException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ClusterNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ClusterNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ConflictExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ConflictException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_InvalidParameterExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new InvalidParameterException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_LimitExceededExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new LimitExceededException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_MissingVersionExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new MissingVersionException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_NamespaceNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new NamespaceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_NoUpdateAvailableExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new NoUpdateAvailableException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_PlatformTaskDefinitionIncompatibilityExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new PlatformTaskDefinitionIncompatibilityException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_PlatformUnknownExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new PlatformUnknownException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ResourceInUseExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ResourceInUseException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ServerExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ServiceDeploymentNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ServiceDeploymentNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ServiceNotActiveExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ServiceNotActiveException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_ServiceNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new ServiceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_TargetNotConnectedExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new TargetNotConnectedException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_TargetNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new TargetNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_TaskSetNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new TaskSetNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_UnsupportedFeatureExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new UnsupportedFeatureException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const de_UpdateInProgressExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = smithyClient._json(body); + const exception = new UpdateInProgressException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized, + }); + return smithyClient.decorateServiceException(exception, body); +}; +const se_CreateCapacityProviderRequest = (input, context) => { + return smithyClient.take(input, { + autoScalingGroupProvider: smithyClient._json, + cluster: [], + managedInstancesProvider: (_) => se_CreateManagedInstancesProviderConfiguration(_), + name: [], + tags: smithyClient._json, + }); +}; +const se_CreatedAt = (input, context) => { + return smithyClient.take(input, { + after: (_) => _.getTime() / 1_000, + before: (_) => _.getTime() / 1_000, + }); +}; +const se_CreateManagedInstancesProviderConfiguration = (input, context) => { + return smithyClient.take(input, { + infrastructureRoleArn: [], + instanceLaunchTemplate: (_) => se_InstanceLaunchTemplate(_), + propagateTags: [], + }); +}; +const se_CreateServiceRequest = (input, context) => { + return smithyClient.take(input, { + availabilityZoneRebalancing: [], + capacityProviderStrategy: smithyClient._json, + clientToken: [], + cluster: [], + deploymentConfiguration: (_) => se_DeploymentConfiguration(_), + deploymentController: smithyClient._json, + desiredCount: [], + enableECSManagedTags: [], + enableExecuteCommand: [], + healthCheckGracePeriodSeconds: [], + launchType: [], + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + placementConstraints: smithyClient._json, + placementStrategy: smithyClient._json, + platformVersion: [], + propagateTags: [], + role: [], + schedulingStrategy: [], + serviceConnectConfiguration: smithyClient._json, + serviceName: [], + serviceRegistries: smithyClient._json, + tags: smithyClient._json, + taskDefinition: [], + volumeConfigurations: smithyClient._json, + vpcLatticeConfigurations: smithyClient._json, + }); +}; +const se_CreateTaskSetRequest = (input, context) => { + return smithyClient.take(input, { + capacityProviderStrategy: smithyClient._json, + clientToken: [], + cluster: [], + externalId: [], + launchType: [], + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + platformVersion: [], + scale: (_) => se_Scale(_), + service: [], + serviceRegistries: smithyClient._json, + tags: smithyClient._json, + taskDefinition: [], + }); +}; +const se_DeploymentConfiguration = (input, context) => { + return smithyClient.take(input, { + alarms: smithyClient._json, + bakeTimeInMinutes: [], + deploymentCircuitBreaker: smithyClient._json, + lifecycleHooks: (_) => se_DeploymentLifecycleHookList(_), + maximumPercent: [], + minimumHealthyPercent: [], + strategy: [], + }); +}; +const se_DeploymentLifecycleHook = (input, context) => { + return smithyClient.take(input, { + hookDetails: (_) => se_HookDetails(_), + hookTargetArn: [], + lifecycleStages: smithyClient._json, + roleArn: [], + }); +}; +const se_DeploymentLifecycleHookList = (input, context) => { + return input + .filter((e) => e != null) + .map((entry) => { + return se_DeploymentLifecycleHook(entry); + }); +}; +const se_HookDetails = (input, context) => { + return input; +}; +const se_InstanceLaunchTemplate = (input, context) => { + return smithyClient.take(input, { + ec2InstanceProfileArn: [], + instanceRequirements: (_) => se_InstanceRequirementsRequest(_), + monitoring: [], + networkConfiguration: smithyClient._json, + storageConfiguration: smithyClient._json, + }); +}; +const se_InstanceLaunchTemplateUpdate = (input, context) => { + return smithyClient.take(input, { + ec2InstanceProfileArn: [], + instanceRequirements: (_) => se_InstanceRequirementsRequest(_), + monitoring: [], + networkConfiguration: smithyClient._json, + storageConfiguration: smithyClient._json, + }); +}; +const se_InstanceRequirementsRequest = (input, context) => { + return smithyClient.take(input, { + acceleratorCount: smithyClient._json, + acceleratorManufacturers: smithyClient._json, + acceleratorNames: smithyClient._json, + acceleratorTotalMemoryMiB: smithyClient._json, + acceleratorTypes: smithyClient._json, + allowedInstanceTypes: smithyClient._json, + bareMetal: [], + baselineEbsBandwidthMbps: smithyClient._json, + burstablePerformance: [], + cpuManufacturers: smithyClient._json, + excludedInstanceTypes: smithyClient._json, + instanceGenerations: smithyClient._json, + localStorage: [], + localStorageTypes: smithyClient._json, + maxSpotPriceAsPercentageOfOptimalOnDemandPrice: [], + memoryGiBPerVCpu: (_) => se_MemoryGiBPerVCpuRequest(_), + memoryMiB: smithyClient._json, + networkBandwidthGbps: (_) => se_NetworkBandwidthGbpsRequest(_), + networkInterfaceCount: smithyClient._json, + onDemandMaxPricePercentageOverLowestPrice: [], + requireHibernateSupport: [], + spotMaxPricePercentageOverLowestPrice: [], + totalLocalStorageGB: (_) => se_TotalLocalStorageGBRequest(_), + vCpuCount: smithyClient._json, + }); +}; +const se_ListServiceDeploymentsRequest = (input, context) => { + return smithyClient.take(input, { + cluster: [], + createdAt: (_) => se_CreatedAt(_), + maxResults: [], + nextToken: [], + service: [], + status: smithyClient._json, + }); +}; +const se_MemoryGiBPerVCpuRequest = (input, context) => { + return smithyClient.take(input, { + max: smithyClient.serializeFloat, + min: smithyClient.serializeFloat, + }); +}; +const se_NetworkBandwidthGbpsRequest = (input, context) => { + return smithyClient.take(input, { + max: smithyClient.serializeFloat, + min: smithyClient.serializeFloat, + }); +}; +const se_RegisterContainerInstanceRequest = (input, context) => { + return smithyClient.take(input, { + attributes: smithyClient._json, + cluster: [], + containerInstanceArn: [], + instanceIdentityDocument: [], + instanceIdentityDocumentSignature: [], + platformDevices: smithyClient._json, + tags: smithyClient._json, + totalResources: (_) => se_Resources(_), + versionInfo: smithyClient._json, + }); +}; +const se_Resource = (input, context) => { + return smithyClient.take(input, { + doubleValue: smithyClient.serializeFloat, + integerValue: [], + longValue: [], + name: [], + stringSetValue: smithyClient._json, + type: [], + }); +}; +const se_Resources = (input, context) => { + return input + .filter((e) => e != null) + .map((entry) => { + return se_Resource(entry); + }); +}; +const se_RunTaskRequest = (input, context) => { + return smithyClient.take(input, { + capacityProviderStrategy: smithyClient._json, + clientToken: [true, (_) => _ ?? uuid.v4()], + cluster: [], + count: [], + enableECSManagedTags: [], + enableExecuteCommand: [], + group: [], + launchType: [], + networkConfiguration: smithyClient._json, + overrides: smithyClient._json, + placementConstraints: smithyClient._json, + placementStrategy: smithyClient._json, + platformVersion: [], + propagateTags: [], + referenceId: [], + startedBy: [], + tags: smithyClient._json, + taskDefinition: [], + volumeConfigurations: smithyClient._json, + }); +}; +const se_Scale = (input, context) => { + return smithyClient.take(input, { + unit: [], + value: smithyClient.serializeFloat, + }); +}; +const se_SubmitTaskStateChangeRequest = (input, context) => { + return smithyClient.take(input, { + attachments: smithyClient._json, + cluster: [], + containers: smithyClient._json, + executionStoppedAt: (_) => _.getTime() / 1_000, + managedAgents: smithyClient._json, + pullStartedAt: (_) => _.getTime() / 1_000, + pullStoppedAt: (_) => _.getTime() / 1_000, + reason: [], + status: [], + task: [], + }); +}; +const se_TotalLocalStorageGBRequest = (input, context) => { + return smithyClient.take(input, { + max: smithyClient.serializeFloat, + min: smithyClient.serializeFloat, + }); +}; +const se_UpdateCapacityProviderRequest = (input, context) => { + return smithyClient.take(input, { + autoScalingGroupProvider: smithyClient._json, + cluster: [], + managedInstancesProvider: (_) => se_UpdateManagedInstancesProviderConfiguration(_), + name: [], + }); +}; +const se_UpdateManagedInstancesProviderConfiguration = (input, context) => { + return smithyClient.take(input, { + infrastructureRoleArn: [], + instanceLaunchTemplate: (_) => se_InstanceLaunchTemplateUpdate(_), + propagateTags: [], + }); +}; +const se_UpdateServiceRequest = (input, context) => { + return smithyClient.take(input, { + availabilityZoneRebalancing: [], + capacityProviderStrategy: smithyClient._json, + cluster: [], + deploymentConfiguration: (_) => se_DeploymentConfiguration(_), + deploymentController: smithyClient._json, + desiredCount: [], + enableECSManagedTags: [], + enableExecuteCommand: [], + forceNewDeployment: [], + healthCheckGracePeriodSeconds: [], + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + placementConstraints: smithyClient._json, + placementStrategy: smithyClient._json, + platformVersion: [], + propagateTags: [], + service: [], + serviceConnectConfiguration: smithyClient._json, + serviceRegistries: smithyClient._json, + taskDefinition: [], + volumeConfigurations: smithyClient._json, + vpcLatticeConfigurations: smithyClient._json, + }); +}; +const se_UpdateTaskSetRequest = (input, context) => { + return smithyClient.take(input, { + cluster: [], + scale: (_) => se_Scale(_), + service: [], + taskSet: [], + }); +}; +const de_CapacityProvider = (output, context) => { + return smithyClient.take(output, { + autoScalingGroupProvider: smithyClient._json, + capacityProviderArn: smithyClient.expectString, + cluster: smithyClient.expectString, + managedInstancesProvider: (_) => de_ManagedInstancesProvider(_), + name: smithyClient.expectString, + status: smithyClient.expectString, + tags: smithyClient._json, + type: smithyClient.expectString, + updateStatus: smithyClient.expectString, + updateStatusReason: smithyClient.expectString, + }); +}; +const de_CapacityProviders = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_CapacityProvider(entry); + }); + return retVal; +}; +const de_Container = (output, context) => { + return smithyClient.take(output, { + containerArn: smithyClient.expectString, + cpu: smithyClient.expectString, + exitCode: smithyClient.expectInt32, + gpuIds: smithyClient._json, + healthStatus: smithyClient.expectString, + image: smithyClient.expectString, + imageDigest: smithyClient.expectString, + lastStatus: smithyClient.expectString, + managedAgents: (_) => de_ManagedAgents(_), + memory: smithyClient.expectString, + memoryReservation: smithyClient.expectString, + name: smithyClient.expectString, + networkBindings: smithyClient._json, + networkInterfaces: smithyClient._json, + reason: smithyClient.expectString, + runtimeId: smithyClient.expectString, + taskArn: smithyClient.expectString, + }); +}; +const de_ContainerInstance = (output, context) => { + return smithyClient.take(output, { + agentConnected: smithyClient.expectBoolean, + agentUpdateStatus: smithyClient.expectString, + attachments: smithyClient._json, + attributes: smithyClient._json, + capacityProviderName: smithyClient.expectString, + containerInstanceArn: smithyClient.expectString, + ec2InstanceId: smithyClient.expectString, + healthStatus: (_) => de_ContainerInstanceHealthStatus(_), + pendingTasksCount: smithyClient.expectInt32, + registeredAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + registeredResources: (_) => de_Resources(_), + remainingResources: (_) => de_Resources(_), + runningTasksCount: smithyClient.expectInt32, + status: smithyClient.expectString, + statusReason: smithyClient.expectString, + tags: smithyClient._json, + version: smithyClient.expectLong, + versionInfo: smithyClient._json, + }); +}; +const de_ContainerInstanceHealthStatus = (output, context) => { + return smithyClient.take(output, { + details: (_) => de_InstanceHealthCheckResultList(_), + overallStatus: smithyClient.expectString, + }); +}; +const de_ContainerInstances = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ContainerInstance(entry); + }); + return retVal; +}; +const de_Containers = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_Container(entry); + }); + return retVal; +}; +const de_CreateCapacityProviderResponse = (output, context) => { + return smithyClient.take(output, { + capacityProvider: (_) => de_CapacityProvider(_), + }); +}; +const de_CreateServiceResponse = (output, context) => { + return smithyClient.take(output, { + service: (_) => de_Service(_), + }); +}; +const de_CreateTaskSetResponse = (output, context) => { + return smithyClient.take(output, { + taskSet: (_) => de_TaskSet(_), + }); +}; +const de_DeleteCapacityProviderResponse = (output, context) => { + return smithyClient.take(output, { + capacityProvider: (_) => de_CapacityProvider(_), + }); +}; +const de_DeleteServiceResponse = (output, context) => { + return smithyClient.take(output, { + service: (_) => de_Service(_), + }); +}; +const de_DeleteTaskDefinitionsResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + taskDefinitions: (_) => de_TaskDefinitionList(_), + }); +}; +const de_DeleteTaskSetResponse = (output, context) => { + return smithyClient.take(output, { + taskSet: (_) => de_TaskSet(_), + }); +}; +const de_Deployment = (output, context) => { + return smithyClient.take(output, { + capacityProviderStrategy: smithyClient._json, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + desiredCount: smithyClient.expectInt32, + failedTasks: smithyClient.expectInt32, + fargateEphemeralStorage: smithyClient._json, + id: smithyClient.expectString, + launchType: smithyClient.expectString, + networkConfiguration: smithyClient._json, + pendingCount: smithyClient.expectInt32, + platformFamily: smithyClient.expectString, + platformVersion: smithyClient.expectString, + rolloutState: smithyClient.expectString, + rolloutStateReason: smithyClient.expectString, + runningCount: smithyClient.expectInt32, + serviceConnectConfiguration: smithyClient._json, + serviceConnectResources: smithyClient._json, + status: smithyClient.expectString, + taskDefinition: smithyClient.expectString, + updatedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + volumeConfigurations: smithyClient._json, + vpcLatticeConfigurations: smithyClient._json, }); - Object.setPrototypeOf(this, _TargetNotFoundException.prototype); - } }; -var ClusterContainsContainerInstancesException = class _ClusterContainsContainerInstancesException extends ECSServiceException { - static { - __name(this, "ClusterContainsContainerInstancesException"); - } - name = "ClusterContainsContainerInstancesException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ClusterContainsContainerInstancesException", - $fault: "client", - ...opts +const de_DeploymentConfiguration = (output, context) => { + return smithyClient.take(output, { + alarms: smithyClient._json, + bakeTimeInMinutes: smithyClient.expectInt32, + deploymentCircuitBreaker: smithyClient._json, + lifecycleHooks: (_) => de_DeploymentLifecycleHookList(_), + maximumPercent: smithyClient.expectInt32, + minimumHealthyPercent: smithyClient.expectInt32, + strategy: smithyClient.expectString, }); - Object.setPrototypeOf(this, _ClusterContainsContainerInstancesException.prototype); - } }; -var ClusterContainsServicesException = class _ClusterContainsServicesException extends ECSServiceException { - static { - __name(this, "ClusterContainsServicesException"); - } - name = "ClusterContainsServicesException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ClusterContainsServicesException", - $fault: "client", - ...opts +const de_DeploymentLifecycleHook = (output, context) => { + return smithyClient.take(output, { + hookDetails: (_) => de_HookDetails(_), + hookTargetArn: smithyClient.expectString, + lifecycleStages: smithyClient._json, + roleArn: smithyClient.expectString, }); - Object.setPrototypeOf(this, _ClusterContainsServicesException.prototype); - } }; -var ClusterContainsTasksException = class _ClusterContainsTasksException extends ECSServiceException { - static { - __name(this, "ClusterContainsTasksException"); - } - name = "ClusterContainsTasksException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ClusterContainsTasksException", - $fault: "client", - ...opts +const de_DeploymentLifecycleHookList = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_DeploymentLifecycleHook(entry); }); - Object.setPrototypeOf(this, _ClusterContainsTasksException.prototype); - } -}; -var Compatibility = { - EC2: "EC2", - EXTERNAL: "EXTERNAL", - FARGATE: "FARGATE" -}; -var ContainerCondition = { - COMPLETE: "COMPLETE", - HEALTHY: "HEALTHY", - START: "START", - SUCCESS: "SUCCESS" -}; -var EnvironmentFileType = { - S3: "s3" -}; -var FirelensConfigurationType = { - FLUENTBIT: "fluentbit", - FLUENTD: "fluentd" -}; -var DeviceCgroupPermission = { - MKNOD: "mknod", - READ: "read", - WRITE: "write" -}; -var ApplicationProtocol = { - GRPC: "grpc", - HTTP: "http", - HTTP2: "http2" -}; -var TransportProtocol = { - TCP: "tcp", - UDP: "udp" -}; -var ResourceType = { - GPU: "GPU", - INFERENCE_ACCELERATOR: "InferenceAccelerator" -}; -var UlimitName = { - CORE: "core", - CPU: "cpu", - DATA: "data", - FSIZE: "fsize", - LOCKS: "locks", - MEMLOCK: "memlock", - MSGQUEUE: "msgqueue", - NICE: "nice", - NOFILE: "nofile", - NPROC: "nproc", - RSS: "rss", - RTPRIO: "rtprio", - RTTIME: "rttime", - SIGPENDING: "sigpending", - STACK: "stack" -}; -var VersionConsistency = { - DISABLED: "disabled", - ENABLED: "enabled" -}; -var IpcMode = { - HOST: "host", - NONE: "none", - TASK: "task" -}; -var NetworkMode = { - AWSVPC: "awsvpc", - BRIDGE: "bridge", - HOST: "host", - NONE: "none" -}; -var PidMode = { - HOST: "host", - TASK: "task" -}; -var TaskDefinitionPlacementConstraintType = { - MEMBER_OF: "memberOf" -}; -var ProxyConfigurationType = { - APPMESH: "APPMESH" -}; -var CPUArchitecture = { - ARM64: "ARM64", - X86_64: "X86_64" -}; -var OSFamily = { - LINUX: "LINUX", - WINDOWS_SERVER_2004_CORE: "WINDOWS_SERVER_2004_CORE", - WINDOWS_SERVER_2016_FULL: "WINDOWS_SERVER_2016_FULL", - WINDOWS_SERVER_2019_CORE: "WINDOWS_SERVER_2019_CORE", - WINDOWS_SERVER_2019_FULL: "WINDOWS_SERVER_2019_FULL", - WINDOWS_SERVER_2022_CORE: "WINDOWS_SERVER_2022_CORE", - WINDOWS_SERVER_2022_FULL: "WINDOWS_SERVER_2022_FULL", - WINDOWS_SERVER_2025_CORE: "WINDOWS_SERVER_2025_CORE", - WINDOWS_SERVER_2025_FULL: "WINDOWS_SERVER_2025_FULL", - WINDOWS_SERVER_20H2_CORE: "WINDOWS_SERVER_20H2_CORE" -}; -var TaskDefinitionStatus = { - ACTIVE: "ACTIVE", - DELETE_IN_PROGRESS: "DELETE_IN_PROGRESS", - INACTIVE: "INACTIVE" -}; -var Scope = { - SHARED: "shared", - TASK: "task" -}; -var EFSAuthorizationConfigIAM = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" -}; -var EFSTransitEncryption = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" -}; -var TaskSetNotFoundException = class _TaskSetNotFoundException extends ECSServiceException { - static { - __name(this, "TaskSetNotFoundException"); - } - name = "TaskSetNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TaskSetNotFoundException", - $fault: "client", - ...opts + return retVal; +}; +const de_Deployments = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_Deployment(entry); }); - Object.setPrototypeOf(this, _TaskSetNotFoundException.prototype); - } -}; -var InstanceHealthCheckState = { - IMPAIRED: "IMPAIRED", - INITIALIZING: "INITIALIZING", - INSUFFICIENT_DATA: "INSUFFICIENT_DATA", - OK: "OK" -}; -var InstanceHealthCheckType = { - CONTAINER_RUNTIME: "CONTAINER_RUNTIME" -}; -var CapacityProviderField = { - TAGS: "TAGS" -}; -var ClusterField = { - ATTACHMENTS: "ATTACHMENTS", - CONFIGURATIONS: "CONFIGURATIONS", - SETTINGS: "SETTINGS", - STATISTICS: "STATISTICS", - TAGS: "TAGS" -}; -var ContainerInstanceField = { - CONTAINER_INSTANCE_HEALTH: "CONTAINER_INSTANCE_HEALTH", - TAGS: "TAGS" -}; -var ServiceDeploymentRollbackMonitorsStatus = { - DISABLED: "DISABLED", - MONITORING: "MONITORING", - MONITORING_COMPLETE: "MONITORING_COMPLETE", - TRIGGERED: "TRIGGERED" -}; -var ServiceDeploymentLifecycleStage = { - BAKE_TIME: "BAKE_TIME", - CLEAN_UP: "CLEAN_UP", - POST_PRODUCTION_TRAFFIC_SHIFT: "POST_PRODUCTION_TRAFFIC_SHIFT", - POST_SCALE_UP: "POST_SCALE_UP", - POST_TEST_TRAFFIC_SHIFT: "POST_TEST_TRAFFIC_SHIFT", - PRE_SCALE_UP: "PRE_SCALE_UP", - PRODUCTION_TRAFFIC_SHIFT: "PRODUCTION_TRAFFIC_SHIFT", - RECONCILE_SERVICE: "RECONCILE_SERVICE", - SCALE_UP: "SCALE_UP", - TEST_TRAFFIC_SHIFT: "TEST_TRAFFIC_SHIFT" -}; -var ServiceDeploymentStatus = { - IN_PROGRESS: "IN_PROGRESS", - PENDING: "PENDING", - ROLLBACK_FAILED: "ROLLBACK_FAILED", - ROLLBACK_IN_PROGRESS: "ROLLBACK_IN_PROGRESS", - ROLLBACK_REQUESTED: "ROLLBACK_REQUESTED", - ROLLBACK_SUCCESSFUL: "ROLLBACK_SUCCESSFUL", - STOPPED: "STOPPED", - STOP_REQUESTED: "STOP_REQUESTED", - SUCCESSFUL: "SUCCESSFUL" -}; -var ServiceField = { - TAGS: "TAGS" -}; -var TaskDefinitionField = { - TAGS: "TAGS" -}; -var TaskField = { - TAGS: "TAGS" -}; -var Connectivity = { - CONNECTED: "CONNECTED", - DISCONNECTED: "DISCONNECTED" -}; -var HealthStatus = { - HEALTHY: "HEALTHY", - UNHEALTHY: "UNHEALTHY", - UNKNOWN: "UNKNOWN" -}; -var ManagedAgentName = { - ExecuteCommandAgent: "ExecuteCommandAgent" -}; -var TaskStopCode = { - ESSENTIAL_CONTAINER_EXITED: "EssentialContainerExited", - SERVICE_SCHEDULER_INITIATED: "ServiceSchedulerInitiated", - SPOT_INTERRUPTION: "SpotInterruption", - TASK_FAILED_TO_START: "TaskFailedToStart", - TERMINATION_NOTICE: "TerminationNotice", - USER_INITIATED: "UserInitiated" -}; -var TaskSetField = { - TAGS: "TAGS" -}; -var TargetNotConnectedException = class _TargetNotConnectedException extends ECSServiceException { - static { - __name(this, "TargetNotConnectedException"); - } - name = "TargetNotConnectedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TargetNotConnectedException", - $fault: "client", - ...opts + return retVal; +}; +const de_DeregisterContainerInstanceResponse = (output, context) => { + return smithyClient.take(output, { + containerInstance: (_) => de_ContainerInstance(_), }); - Object.setPrototypeOf(this, _TargetNotConnectedException.prototype); - } }; -var ResourceNotFoundException = class _ResourceNotFoundException extends ECSServiceException { - static { - __name(this, "ResourceNotFoundException"); - } - name = "ResourceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts +const de_DeregisterTaskDefinitionResponse = (output, context) => { + return smithyClient.take(output, { + taskDefinition: (_) => de_TaskDefinition(_), }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } }; -var ContainerInstanceStatus = { - ACTIVE: "ACTIVE", - DEREGISTERING: "DEREGISTERING", - DRAINING: "DRAINING", - REGISTERING: "REGISTERING", - REGISTRATION_FAILED: "REGISTRATION_FAILED" +const de_DescribeCapacityProvidersResponse = (output, context) => { + return smithyClient.take(output, { + capacityProviders: (_) => de_CapacityProviders(_), + failures: smithyClient._json, + nextToken: smithyClient.expectString, + }); }; -var TaskDefinitionFamilyStatus = { - ACTIVE: "ACTIVE", - ALL: "ALL", - INACTIVE: "INACTIVE" +const de_DescribeContainerInstancesResponse = (output, context) => { + return smithyClient.take(output, { + containerInstances: (_) => de_ContainerInstances(_), + failures: smithyClient._json, + }); }; -var SortOrder = { - ASC: "ASC", - DESC: "DESC" +const de_DescribeServiceDeploymentsResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + serviceDeployments: (_) => de_ServiceDeployments(_), + }); }; -var DesiredStatus = { - PENDING: "PENDING", - RUNNING: "RUNNING", - STOPPED: "STOPPED" +const de_DescribeServiceRevisionsResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + serviceRevisions: (_) => de_ServiceRevisions(_), + }); }; -var AttributeLimitExceededException = class _AttributeLimitExceededException extends ECSServiceException { - static { - __name(this, "AttributeLimitExceededException"); - } - name = "AttributeLimitExceededException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AttributeLimitExceededException", - $fault: "client", - ...opts +const de_DescribeServicesResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + services: (_) => de_Services(_), }); - Object.setPrototypeOf(this, _AttributeLimitExceededException.prototype); - } }; -var ResourceInUseException = class _ResourceInUseException extends ECSServiceException { - static { - __name(this, "ResourceInUseException"); - } - name = "ResourceInUseException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceInUseException", - $fault: "client", - ...opts +const de_DescribeTaskDefinitionResponse = (output, context) => { + return smithyClient.take(output, { + tags: smithyClient._json, + taskDefinition: (_) => de_TaskDefinition(_), }); - Object.setPrototypeOf(this, _ResourceInUseException.prototype); - } }; -var PlatformDeviceType = { - GPU: "GPU" +const de_DescribeTaskSetsResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + taskSets: (_) => de_TaskSets(_), + }); }; -var BlockedException = class _BlockedException extends ECSServiceException { - static { - __name(this, "BlockedException"); - } - name = "BlockedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "BlockedException", - $fault: "client", - ...opts +const de_DescribeTasksResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + tasks: (_) => de_Tasks(_), }); - Object.setPrototypeOf(this, _BlockedException.prototype); - } }; -var ConflictException = class _ConflictException extends ECSServiceException { - static { - __name(this, "ConflictException"); - } - name = "ConflictException"; - $fault = "client"; - /** - *

The existing task ARNs which are already associated with the - * clientToken.

- * @public - */ - resourceIds; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ConflictException", - $fault: "client", - ...opts +const de_GetTaskProtectionResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + protectedTasks: (_) => de_ProtectedTasks(_), }); - Object.setPrototypeOf(this, _ConflictException.prototype); - this.resourceIds = opts.resourceIds; - } }; -var ServiceDeploymentNotFoundException = class _ServiceDeploymentNotFoundException extends ECSServiceException { - static { - __name(this, "ServiceDeploymentNotFoundException"); - } - name = "ServiceDeploymentNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ServiceDeploymentNotFoundException", - $fault: "client", - ...opts +const de_HookDetails = (output, context) => { + return output; +}; +const de_InstanceHealthCheckResult = (output, context) => { + return smithyClient.take(output, { + lastStatusChange: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + lastUpdated: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + status: smithyClient.expectString, + type: smithyClient.expectString, + }); +}; +const de_InstanceHealthCheckResultList = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_InstanceHealthCheckResult(entry); + }); + return retVal; +}; +const de_InstanceLaunchTemplate = (output, context) => { + return smithyClient.take(output, { + ec2InstanceProfileArn: smithyClient.expectString, + instanceRequirements: (_) => de_InstanceRequirementsRequest(_), + monitoring: smithyClient.expectString, + networkConfiguration: smithyClient._json, + storageConfiguration: smithyClient._json, + }); +}; +const de_InstanceRequirementsRequest = (output, context) => { + return smithyClient.take(output, { + acceleratorCount: smithyClient._json, + acceleratorManufacturers: smithyClient._json, + acceleratorNames: smithyClient._json, + acceleratorTotalMemoryMiB: smithyClient._json, + acceleratorTypes: smithyClient._json, + allowedInstanceTypes: smithyClient._json, + bareMetal: smithyClient.expectString, + baselineEbsBandwidthMbps: smithyClient._json, + burstablePerformance: smithyClient.expectString, + cpuManufacturers: smithyClient._json, + excludedInstanceTypes: smithyClient._json, + instanceGenerations: smithyClient._json, + localStorage: smithyClient.expectString, + localStorageTypes: smithyClient._json, + maxSpotPriceAsPercentageOfOptimalOnDemandPrice: smithyClient.expectInt32, + memoryGiBPerVCpu: (_) => de_MemoryGiBPerVCpuRequest(_), + memoryMiB: smithyClient._json, + networkBandwidthGbps: (_) => de_NetworkBandwidthGbpsRequest(_), + networkInterfaceCount: smithyClient._json, + onDemandMaxPricePercentageOverLowestPrice: smithyClient.expectInt32, + requireHibernateSupport: smithyClient.expectBoolean, + spotMaxPricePercentageOverLowestPrice: smithyClient.expectInt32, + totalLocalStorageGB: (_) => de_TotalLocalStorageGBRequest(_), + vCpuCount: smithyClient._json, + }); +}; +const de_ListServiceDeploymentsResponse = (output, context) => { + return smithyClient.take(output, { + nextToken: smithyClient.expectString, + serviceDeployments: (_) => de_ServiceDeploymentsBrief(_), + }); +}; +const de_ManagedAgent = (output, context) => { + return smithyClient.take(output, { + lastStartedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + lastStatus: smithyClient.expectString, + name: smithyClient.expectString, + reason: smithyClient.expectString, + }); +}; +const de_ManagedAgents = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ManagedAgent(entry); + }); + return retVal; +}; +const de_ManagedInstancesProvider = (output, context) => { + return smithyClient.take(output, { + infrastructureRoleArn: smithyClient.expectString, + instanceLaunchTemplate: (_) => de_InstanceLaunchTemplate(_), + propagateTags: smithyClient.expectString, + }); +}; +const de_MemoryGiBPerVCpuRequest = (output, context) => { + return smithyClient.take(output, { + max: smithyClient.limitedParseDouble, + min: smithyClient.limitedParseDouble, + }); +}; +const de_NetworkBandwidthGbpsRequest = (output, context) => { + return smithyClient.take(output, { + max: smithyClient.limitedParseDouble, + min: smithyClient.limitedParseDouble, + }); +}; +const de_ProtectedTask = (output, context) => { + return smithyClient.take(output, { + expirationDate: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + protectionEnabled: smithyClient.expectBoolean, + taskArn: smithyClient.expectString, + }); +}; +const de_ProtectedTasks = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ProtectedTask(entry); + }); + return retVal; +}; +const de_RegisterContainerInstanceResponse = (output, context) => { + return smithyClient.take(output, { + containerInstance: (_) => de_ContainerInstance(_), + }); +}; +const de_RegisterTaskDefinitionResponse = (output, context) => { + return smithyClient.take(output, { + tags: smithyClient._json, + taskDefinition: (_) => de_TaskDefinition(_), + }); +}; +const de_Resource = (output, context) => { + return smithyClient.take(output, { + doubleValue: smithyClient.limitedParseDouble, + integerValue: smithyClient.expectInt32, + longValue: smithyClient.expectLong, + name: smithyClient.expectString, + stringSetValue: smithyClient._json, + type: smithyClient.expectString, + }); +}; +const de_Resources = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_Resource(entry); + }); + return retVal; +}; +const de_Rollback = (output, context) => { + return smithyClient.take(output, { + reason: smithyClient.expectString, + serviceRevisionArn: smithyClient.expectString, + startedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + }); +}; +const de_RunTaskResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + tasks: (_) => de_Tasks(_), + }); +}; +const de_Scale = (output, context) => { + return smithyClient.take(output, { + unit: smithyClient.expectString, + value: smithyClient.limitedParseDouble, + }); +}; +const de_Service = (output, context) => { + return smithyClient.take(output, { + availabilityZoneRebalancing: smithyClient.expectString, + capacityProviderStrategy: smithyClient._json, + clusterArn: smithyClient.expectString, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + createdBy: smithyClient.expectString, + deploymentConfiguration: (_) => de_DeploymentConfiguration(_), + deploymentController: smithyClient._json, + deployments: (_) => de_Deployments(_), + desiredCount: smithyClient.expectInt32, + enableECSManagedTags: smithyClient.expectBoolean, + enableExecuteCommand: smithyClient.expectBoolean, + events: (_) => de_ServiceEvents(_), + healthCheckGracePeriodSeconds: smithyClient.expectInt32, + launchType: smithyClient.expectString, + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + pendingCount: smithyClient.expectInt32, + placementConstraints: smithyClient._json, + placementStrategy: smithyClient._json, + platformFamily: smithyClient.expectString, + platformVersion: smithyClient.expectString, + propagateTags: smithyClient.expectString, + roleArn: smithyClient.expectString, + runningCount: smithyClient.expectInt32, + schedulingStrategy: smithyClient.expectString, + serviceArn: smithyClient.expectString, + serviceName: smithyClient.expectString, + serviceRegistries: smithyClient._json, + status: smithyClient.expectString, + tags: smithyClient._json, + taskDefinition: smithyClient.expectString, + taskSets: (_) => de_TaskSets(_), + }); +}; +const de_ServiceDeployment = (output, context) => { + return smithyClient.take(output, { + alarms: smithyClient._json, + clusterArn: smithyClient.expectString, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + deploymentCircuitBreaker: smithyClient._json, + deploymentConfiguration: (_) => de_DeploymentConfiguration(_), + finishedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + lifecycleStage: smithyClient.expectString, + rollback: (_) => de_Rollback(_), + serviceArn: smithyClient.expectString, + serviceDeploymentArn: smithyClient.expectString, + sourceServiceRevisions: smithyClient._json, + startedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + status: smithyClient.expectString, + statusReason: smithyClient.expectString, + stoppedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + targetServiceRevision: smithyClient._json, + updatedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + }); +}; +const de_ServiceDeploymentBrief = (output, context) => { + return smithyClient.take(output, { + clusterArn: smithyClient.expectString, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + finishedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + serviceArn: smithyClient.expectString, + serviceDeploymentArn: smithyClient.expectString, + startedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + status: smithyClient.expectString, + statusReason: smithyClient.expectString, + targetServiceRevisionArn: smithyClient.expectString, + }); +}; +const de_ServiceDeployments = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ServiceDeployment(entry); + }); + return retVal; +}; +const de_ServiceDeploymentsBrief = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ServiceDeploymentBrief(entry); + }); + return retVal; +}; +const de_ServiceEvent = (output, context) => { + return smithyClient.take(output, { + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + id: smithyClient.expectString, + message: smithyClient.expectString, + }); +}; +const de_ServiceEvents = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ServiceEvent(entry); + }); + return retVal; +}; +const de_ServiceRevision = (output, context) => { + return smithyClient.take(output, { + capacityProviderStrategy: smithyClient._json, + clusterArn: smithyClient.expectString, + containerImages: smithyClient._json, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + fargateEphemeralStorage: smithyClient._json, + guardDutyEnabled: smithyClient.expectBoolean, + launchType: smithyClient.expectString, + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + platformFamily: smithyClient.expectString, + platformVersion: smithyClient.expectString, + resolvedConfiguration: smithyClient._json, + serviceArn: smithyClient.expectString, + serviceConnectConfiguration: smithyClient._json, + serviceRegistries: smithyClient._json, + serviceRevisionArn: smithyClient.expectString, + taskDefinition: smithyClient.expectString, + volumeConfigurations: smithyClient._json, + vpcLatticeConfigurations: smithyClient._json, + }); +}; +const de_ServiceRevisions = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_ServiceRevision(entry); + }); + return retVal; +}; +const de_Services = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_Service(entry); + }); + return retVal; +}; +const de_StartTaskResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + tasks: (_) => de_Tasks(_), + }); +}; +const de_StopTaskResponse = (output, context) => { + return smithyClient.take(output, { + task: (_) => de_Task(_), + }); +}; +const de_Task = (output, context) => { + return smithyClient.take(output, { + attachments: smithyClient._json, + attributes: smithyClient._json, + availabilityZone: smithyClient.expectString, + capacityProviderName: smithyClient.expectString, + clusterArn: smithyClient.expectString, + connectivity: smithyClient.expectString, + connectivityAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + containerInstanceArn: smithyClient.expectString, + containers: (_) => de_Containers(_), + cpu: smithyClient.expectString, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + desiredStatus: smithyClient.expectString, + enableExecuteCommand: smithyClient.expectBoolean, + ephemeralStorage: smithyClient._json, + executionStoppedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + fargateEphemeralStorage: smithyClient._json, + group: smithyClient.expectString, + healthStatus: smithyClient.expectString, + inferenceAccelerators: smithyClient._json, + lastStatus: smithyClient.expectString, + launchType: smithyClient.expectString, + memory: smithyClient.expectString, + overrides: smithyClient._json, + platformFamily: smithyClient.expectString, + platformVersion: smithyClient.expectString, + pullStartedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + pullStoppedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + startedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + startedBy: smithyClient.expectString, + stopCode: smithyClient.expectString, + stoppedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + stoppedReason: smithyClient.expectString, + stoppingAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + tags: smithyClient._json, + taskArn: smithyClient.expectString, + taskDefinitionArn: smithyClient.expectString, + version: smithyClient.expectLong, + }); +}; +const de_TaskDefinition = (output, context) => { + return smithyClient.take(output, { + compatibilities: smithyClient._json, + containerDefinitions: smithyClient._json, + cpu: smithyClient.expectString, + deregisteredAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + enableFaultInjection: smithyClient.expectBoolean, + ephemeralStorage: smithyClient._json, + executionRoleArn: smithyClient.expectString, + family: smithyClient.expectString, + inferenceAccelerators: smithyClient._json, + ipcMode: smithyClient.expectString, + memory: smithyClient.expectString, + networkMode: smithyClient.expectString, + pidMode: smithyClient.expectString, + placementConstraints: smithyClient._json, + proxyConfiguration: smithyClient._json, + registeredAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + registeredBy: smithyClient.expectString, + requiresAttributes: smithyClient._json, + requiresCompatibilities: smithyClient._json, + revision: smithyClient.expectInt32, + runtimePlatform: smithyClient._json, + status: smithyClient.expectString, + taskDefinitionArn: smithyClient.expectString, + taskRoleArn: smithyClient.expectString, + volumes: smithyClient._json, + }); +}; +const de_TaskDefinitionList = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_TaskDefinition(entry); + }); + return retVal; +}; +const de_Tasks = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_Task(entry); + }); + return retVal; +}; +const de_TaskSet = (output, context) => { + return smithyClient.take(output, { + capacityProviderStrategy: smithyClient._json, + clusterArn: smithyClient.expectString, + computedDesiredCount: smithyClient.expectInt32, + createdAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + externalId: smithyClient.expectString, + fargateEphemeralStorage: smithyClient._json, + id: smithyClient.expectString, + launchType: smithyClient.expectString, + loadBalancers: smithyClient._json, + networkConfiguration: smithyClient._json, + pendingCount: smithyClient.expectInt32, + platformFamily: smithyClient.expectString, + platformVersion: smithyClient.expectString, + runningCount: smithyClient.expectInt32, + scale: (_) => de_Scale(_), + serviceArn: smithyClient.expectString, + serviceRegistries: smithyClient._json, + stabilityStatus: smithyClient.expectString, + stabilityStatusAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + startedBy: smithyClient.expectString, + status: smithyClient.expectString, + tags: smithyClient._json, + taskDefinition: smithyClient.expectString, + taskSetArn: smithyClient.expectString, + updatedAt: (_) => smithyClient.expectNonNull(smithyClient.parseEpochTimestamp(smithyClient.expectNumber(_))), + }); +}; +const de_TaskSets = (output, context) => { + const retVal = (output || []) + .filter((e) => e != null) + .map((entry) => { + return de_TaskSet(entry); + }); + return retVal; +}; +const de_TotalLocalStorageGBRequest = (output, context) => { + return smithyClient.take(output, { + max: smithyClient.limitedParseDouble, + min: smithyClient.limitedParseDouble, + }); +}; +const de_UpdateCapacityProviderResponse = (output, context) => { + return smithyClient.take(output, { + capacityProvider: (_) => de_CapacityProvider(_), + }); +}; +const de_UpdateContainerAgentResponse = (output, context) => { + return smithyClient.take(output, { + containerInstance: (_) => de_ContainerInstance(_), + }); +}; +const de_UpdateContainerInstancesStateResponse = (output, context) => { + return smithyClient.take(output, { + containerInstances: (_) => de_ContainerInstances(_), + failures: smithyClient._json, + }); +}; +const de_UpdateServicePrimaryTaskSetResponse = (output, context) => { + return smithyClient.take(output, { + taskSet: (_) => de_TaskSet(_), + }); +}; +const de_UpdateServiceResponse = (output, context) => { + return smithyClient.take(output, { + service: (_) => de_Service(_), + }); +}; +const de_UpdateTaskProtectionResponse = (output, context) => { + return smithyClient.take(output, { + failures: smithyClient._json, + protectedTasks: (_) => de_ProtectedTasks(_), + }); +}; +const de_UpdateTaskSetResponse = (output, context) => { + return smithyClient.take(output, { + taskSet: (_) => de_TaskSet(_), }); - Object.setPrototypeOf(this, _ServiceDeploymentNotFoundException.prototype); - } }; -var StopServiceDeploymentStopType = { - ABORT: "ABORT", - ROLLBACK: "ROLLBACK" +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); +const throwDefaultError = smithyClient.withBaseException(ECSServiceException); +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers, + }; + if (body !== undefined) { + contents.body = body; + } + return new protocolHttp.HttpRequest(contents); }; -var SessionFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.tokenValue && { tokenValue: import_smithy_client.SENSITIVE_STRING } -}), "SessionFilterSensitiveLog"); -var ExecuteCommandResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.session && { session: SessionFilterSensitiveLog(obj.session) } -}), "ExecuteCommandResponseFilterSensitiveLog"); +function sharedHeaders(operation) { + return { + "content-type": "application/x-amz-json-1.1", + "x-amz-target": `AmazonEC2ContainerServiceV20141113.${operation}`, + }; +} -// src/models/models_1.ts -var MissingVersionException = class _MissingVersionException extends ECSServiceException { - static { - __name(this, "MissingVersionException"); - } - name = "MissingVersionException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MissingVersionException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MissingVersionException.prototype); - } +class CreateCapacityProviderCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "CreateCapacityProvider", {}) + .n("ECSClient", "CreateCapacityProviderCommand") + .f(void 0, void 0) + .ser(se_CreateCapacityProviderCommand) + .de(de_CreateCapacityProviderCommand) + .build() { +} + +class CreateClusterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "CreateCluster", {}) + .n("ECSClient", "CreateClusterCommand") + .f(void 0, void 0) + .ser(se_CreateClusterCommand) + .de(de_CreateClusterCommand) + .build() { +} + +class CreateServiceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "CreateService", {}) + .n("ECSClient", "CreateServiceCommand") + .f(void 0, void 0) + .ser(se_CreateServiceCommand) + .de(de_CreateServiceCommand) + .build() { +} + +class CreateTaskSetCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "CreateTaskSet", {}) + .n("ECSClient", "CreateTaskSetCommand") + .f(void 0, void 0) + .ser(se_CreateTaskSetCommand) + .de(de_CreateTaskSetCommand) + .build() { +} + +class DeleteAccountSettingCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteAccountSetting", {}) + .n("ECSClient", "DeleteAccountSettingCommand") + .f(void 0, void 0) + .ser(se_DeleteAccountSettingCommand) + .de(de_DeleteAccountSettingCommand) + .build() { +} + +class DeleteAttributesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteAttributes", {}) + .n("ECSClient", "DeleteAttributesCommand") + .f(void 0, void 0) + .ser(se_DeleteAttributesCommand) + .de(de_DeleteAttributesCommand) + .build() { +} + +class DeleteCapacityProviderCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteCapacityProvider", {}) + .n("ECSClient", "DeleteCapacityProviderCommand") + .f(void 0, void 0) + .ser(se_DeleteCapacityProviderCommand) + .de(de_DeleteCapacityProviderCommand) + .build() { +} + +class DeleteClusterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteCluster", {}) + .n("ECSClient", "DeleteClusterCommand") + .f(void 0, void 0) + .ser(se_DeleteClusterCommand) + .de(de_DeleteClusterCommand) + .build() { +} + +class DeleteServiceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteService", {}) + .n("ECSClient", "DeleteServiceCommand") + .f(void 0, void 0) + .ser(se_DeleteServiceCommand) + .de(de_DeleteServiceCommand) + .build() { +} + +class DeleteTaskDefinitionsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteTaskDefinitions", {}) + .n("ECSClient", "DeleteTaskDefinitionsCommand") + .f(void 0, void 0) + .ser(se_DeleteTaskDefinitionsCommand) + .de(de_DeleteTaskDefinitionsCommand) + .build() { +} + +class DeleteTaskSetCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeleteTaskSet", {}) + .n("ECSClient", "DeleteTaskSetCommand") + .f(void 0, void 0) + .ser(se_DeleteTaskSetCommand) + .de(de_DeleteTaskSetCommand) + .build() { +} + +class DeregisterContainerInstanceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeregisterContainerInstance", {}) + .n("ECSClient", "DeregisterContainerInstanceCommand") + .f(void 0, void 0) + .ser(se_DeregisterContainerInstanceCommand) + .de(de_DeregisterContainerInstanceCommand) + .build() { +} + +class DeregisterTaskDefinitionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DeregisterTaskDefinition", {}) + .n("ECSClient", "DeregisterTaskDefinitionCommand") + .f(void 0, void 0) + .ser(se_DeregisterTaskDefinitionCommand) + .de(de_DeregisterTaskDefinitionCommand) + .build() { +} + +class DescribeCapacityProvidersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeCapacityProviders", {}) + .n("ECSClient", "DescribeCapacityProvidersCommand") + .f(void 0, void 0) + .ser(se_DescribeCapacityProvidersCommand) + .de(de_DescribeCapacityProvidersCommand) + .build() { +} + +class DescribeClustersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeClusters", {}) + .n("ECSClient", "DescribeClustersCommand") + .f(void 0, void 0) + .ser(se_DescribeClustersCommand) + .de(de_DescribeClustersCommand) + .build() { +} + +class DescribeContainerInstancesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeContainerInstances", {}) + .n("ECSClient", "DescribeContainerInstancesCommand") + .f(void 0, void 0) + .ser(se_DescribeContainerInstancesCommand) + .de(de_DescribeContainerInstancesCommand) + .build() { +} + +class DescribeServiceDeploymentsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeServiceDeployments", {}) + .n("ECSClient", "DescribeServiceDeploymentsCommand") + .f(void 0, void 0) + .ser(se_DescribeServiceDeploymentsCommand) + .de(de_DescribeServiceDeploymentsCommand) + .build() { +} + +class DescribeServiceRevisionsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeServiceRevisions", {}) + .n("ECSClient", "DescribeServiceRevisionsCommand") + .f(void 0, void 0) + .ser(se_DescribeServiceRevisionsCommand) + .de(de_DescribeServiceRevisionsCommand) + .build() { +} + +class DescribeServicesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeServices", {}) + .n("ECSClient", "DescribeServicesCommand") + .f(void 0, void 0) + .ser(se_DescribeServicesCommand) + .de(de_DescribeServicesCommand) + .build() { +} + +class DescribeTaskDefinitionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeTaskDefinition", {}) + .n("ECSClient", "DescribeTaskDefinitionCommand") + .f(void 0, void 0) + .ser(se_DescribeTaskDefinitionCommand) + .de(de_DescribeTaskDefinitionCommand) + .build() { +} + +class DescribeTasksCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeTasks", {}) + .n("ECSClient", "DescribeTasksCommand") + .f(void 0, void 0) + .ser(se_DescribeTasksCommand) + .de(de_DescribeTasksCommand) + .build() { +} + +class DescribeTaskSetsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DescribeTaskSets", {}) + .n("ECSClient", "DescribeTaskSetsCommand") + .f(void 0, void 0) + .ser(se_DescribeTaskSetsCommand) + .de(de_DescribeTaskSetsCommand) + .build() { +} + +class DiscoverPollEndpointCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "DiscoverPollEndpoint", {}) + .n("ECSClient", "DiscoverPollEndpointCommand") + .f(void 0, void 0) + .ser(se_DiscoverPollEndpointCommand) + .de(de_DiscoverPollEndpointCommand) + .build() { +} + +class ExecuteCommandCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ExecuteCommand", {}) + .n("ECSClient", "ExecuteCommandCommand") + .f(void 0, ExecuteCommandResponseFilterSensitiveLog) + .ser(se_ExecuteCommandCommand) + .de(de_ExecuteCommandCommand) + .build() { +} + +class GetTaskProtectionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "GetTaskProtection", {}) + .n("ECSClient", "GetTaskProtectionCommand") + .f(void 0, void 0) + .ser(se_GetTaskProtectionCommand) + .de(de_GetTaskProtectionCommand) + .build() { +} + +class ListAccountSettingsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListAccountSettings", {}) + .n("ECSClient", "ListAccountSettingsCommand") + .f(void 0, void 0) + .ser(se_ListAccountSettingsCommand) + .de(de_ListAccountSettingsCommand) + .build() { +} + +class ListAttributesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListAttributes", {}) + .n("ECSClient", "ListAttributesCommand") + .f(void 0, void 0) + .ser(se_ListAttributesCommand) + .de(de_ListAttributesCommand) + .build() { +} + +class ListClustersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListClusters", {}) + .n("ECSClient", "ListClustersCommand") + .f(void 0, void 0) + .ser(se_ListClustersCommand) + .de(de_ListClustersCommand) + .build() { +} + +class ListContainerInstancesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListContainerInstances", {}) + .n("ECSClient", "ListContainerInstancesCommand") + .f(void 0, void 0) + .ser(se_ListContainerInstancesCommand) + .de(de_ListContainerInstancesCommand) + .build() { +} + +class ListServiceDeploymentsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListServiceDeployments", {}) + .n("ECSClient", "ListServiceDeploymentsCommand") + .f(void 0, void 0) + .ser(se_ListServiceDeploymentsCommand) + .de(de_ListServiceDeploymentsCommand) + .build() { +} + +class ListServicesByNamespaceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListServicesByNamespace", {}) + .n("ECSClient", "ListServicesByNamespaceCommand") + .f(void 0, void 0) + .ser(se_ListServicesByNamespaceCommand) + .de(de_ListServicesByNamespaceCommand) + .build() { +} + +class ListServicesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListServices", {}) + .n("ECSClient", "ListServicesCommand") + .f(void 0, void 0) + .ser(se_ListServicesCommand) + .de(de_ListServicesCommand) + .build() { +} + +class ListTagsForResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListTagsForResource", {}) + .n("ECSClient", "ListTagsForResourceCommand") + .f(void 0, void 0) + .ser(se_ListTagsForResourceCommand) + .de(de_ListTagsForResourceCommand) + .build() { +} + +class ListTaskDefinitionFamiliesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListTaskDefinitionFamilies", {}) + .n("ECSClient", "ListTaskDefinitionFamiliesCommand") + .f(void 0, void 0) + .ser(se_ListTaskDefinitionFamiliesCommand) + .de(de_ListTaskDefinitionFamiliesCommand) + .build() { +} + +class ListTaskDefinitionsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListTaskDefinitions", {}) + .n("ECSClient", "ListTaskDefinitionsCommand") + .f(void 0, void 0) + .ser(se_ListTaskDefinitionsCommand) + .de(de_ListTaskDefinitionsCommand) + .build() { +} + +class ListTasksCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "ListTasks", {}) + .n("ECSClient", "ListTasksCommand") + .f(void 0, void 0) + .ser(se_ListTasksCommand) + .de(de_ListTasksCommand) + .build() { +} + +class PutAccountSettingCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "PutAccountSetting", {}) + .n("ECSClient", "PutAccountSettingCommand") + .f(void 0, void 0) + .ser(se_PutAccountSettingCommand) + .de(de_PutAccountSettingCommand) + .build() { +} + +class PutAccountSettingDefaultCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "PutAccountSettingDefault", {}) + .n("ECSClient", "PutAccountSettingDefaultCommand") + .f(void 0, void 0) + .ser(se_PutAccountSettingDefaultCommand) + .de(de_PutAccountSettingDefaultCommand) + .build() { +} + +class PutAttributesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "PutAttributes", {}) + .n("ECSClient", "PutAttributesCommand") + .f(void 0, void 0) + .ser(se_PutAttributesCommand) + .de(de_PutAttributesCommand) + .build() { +} + +class PutClusterCapacityProvidersCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "PutClusterCapacityProviders", {}) + .n("ECSClient", "PutClusterCapacityProvidersCommand") + .f(void 0, void 0) + .ser(se_PutClusterCapacityProvidersCommand) + .de(de_PutClusterCapacityProvidersCommand) + .build() { +} + +class RegisterContainerInstanceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "RegisterContainerInstance", {}) + .n("ECSClient", "RegisterContainerInstanceCommand") + .f(void 0, void 0) + .ser(se_RegisterContainerInstanceCommand) + .de(de_RegisterContainerInstanceCommand) + .build() { +} + +class RegisterTaskDefinitionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "RegisterTaskDefinition", {}) + .n("ECSClient", "RegisterTaskDefinitionCommand") + .f(void 0, void 0) + .ser(se_RegisterTaskDefinitionCommand) + .de(de_RegisterTaskDefinitionCommand) + .build() { +} + +class RunTaskCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "RunTask", {}) + .n("ECSClient", "RunTaskCommand") + .f(void 0, void 0) + .ser(se_RunTaskCommand) + .de(de_RunTaskCommand) + .build() { +} + +class StartTaskCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "StartTask", {}) + .n("ECSClient", "StartTaskCommand") + .f(void 0, void 0) + .ser(se_StartTaskCommand) + .de(de_StartTaskCommand) + .build() { +} + +class StopServiceDeploymentCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "StopServiceDeployment", {}) + .n("ECSClient", "StopServiceDeploymentCommand") + .f(void 0, void 0) + .ser(se_StopServiceDeploymentCommand) + .de(de_StopServiceDeploymentCommand) + .build() { +} + +class StopTaskCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "StopTask", {}) + .n("ECSClient", "StopTaskCommand") + .f(void 0, void 0) + .ser(se_StopTaskCommand) + .de(de_StopTaskCommand) + .build() { +} + +class SubmitAttachmentStateChangesCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "SubmitAttachmentStateChanges", {}) + .n("ECSClient", "SubmitAttachmentStateChangesCommand") + .f(void 0, void 0) + .ser(se_SubmitAttachmentStateChangesCommand) + .de(de_SubmitAttachmentStateChangesCommand) + .build() { +} + +class SubmitContainerStateChangeCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "SubmitContainerStateChange", {}) + .n("ECSClient", "SubmitContainerStateChangeCommand") + .f(void 0, void 0) + .ser(se_SubmitContainerStateChangeCommand) + .de(de_SubmitContainerStateChangeCommand) + .build() { +} + +class SubmitTaskStateChangeCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "SubmitTaskStateChange", {}) + .n("ECSClient", "SubmitTaskStateChangeCommand") + .f(void 0, void 0) + .ser(se_SubmitTaskStateChangeCommand) + .de(de_SubmitTaskStateChangeCommand) + .build() { +} + +class TagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "TagResource", {}) + .n("ECSClient", "TagResourceCommand") + .f(void 0, void 0) + .ser(se_TagResourceCommand) + .de(de_TagResourceCommand) + .build() { +} + +class UntagResourceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UntagResource", {}) + .n("ECSClient", "UntagResourceCommand") + .f(void 0, void 0) + .ser(se_UntagResourceCommand) + .de(de_UntagResourceCommand) + .build() { +} + +class UpdateCapacityProviderCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateCapacityProvider", {}) + .n("ECSClient", "UpdateCapacityProviderCommand") + .f(void 0, void 0) + .ser(se_UpdateCapacityProviderCommand) + .de(de_UpdateCapacityProviderCommand) + .build() { +} + +class UpdateClusterCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateCluster", {}) + .n("ECSClient", "UpdateClusterCommand") + .f(void 0, void 0) + .ser(se_UpdateClusterCommand) + .de(de_UpdateClusterCommand) + .build() { +} + +class UpdateClusterSettingsCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateClusterSettings", {}) + .n("ECSClient", "UpdateClusterSettingsCommand") + .f(void 0, void 0) + .ser(se_UpdateClusterSettingsCommand) + .de(de_UpdateClusterSettingsCommand) + .build() { +} + +class UpdateContainerAgentCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateContainerAgent", {}) + .n("ECSClient", "UpdateContainerAgentCommand") + .f(void 0, void 0) + .ser(se_UpdateContainerAgentCommand) + .de(de_UpdateContainerAgentCommand) + .build() { +} + +class UpdateContainerInstancesStateCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateContainerInstancesState", {}) + .n("ECSClient", "UpdateContainerInstancesStateCommand") + .f(void 0, void 0) + .ser(se_UpdateContainerInstancesStateCommand) + .de(de_UpdateContainerInstancesStateCommand) + .build() { +} + +class UpdateServiceCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateService", {}) + .n("ECSClient", "UpdateServiceCommand") + .f(void 0, void 0) + .ser(se_UpdateServiceCommand) + .de(de_UpdateServiceCommand) + .build() { +} + +class UpdateServicePrimaryTaskSetCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateServicePrimaryTaskSet", {}) + .n("ECSClient", "UpdateServicePrimaryTaskSetCommand") + .f(void 0, void 0) + .ser(se_UpdateServicePrimaryTaskSetCommand) + .de(de_UpdateServicePrimaryTaskSetCommand) + .build() { +} + +class UpdateTaskProtectionCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateTaskProtection", {}) + .n("ECSClient", "UpdateTaskProtectionCommand") + .f(void 0, void 0) + .ser(se_UpdateTaskProtectionCommand) + .de(de_UpdateTaskProtectionCommand) + .build() { +} + +class UpdateTaskSetCommand extends smithyClient.Command + .classBuilder() + .ep(commonParams) + .m(function (Command, cs, config, o) { + return [ + middlewareSerde.getSerdePlugin(config, this.serialize, this.deserialize), + middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + ]; +}) + .s("AmazonEC2ContainerServiceV20141113", "UpdateTaskSet", {}) + .n("ECSClient", "UpdateTaskSetCommand") + .f(void 0, void 0) + .ser(se_UpdateTaskSetCommand) + .de(de_UpdateTaskSetCommand) + .build() { +} + +const commands = { + CreateCapacityProviderCommand, + CreateClusterCommand, + CreateServiceCommand, + CreateTaskSetCommand, + DeleteAccountSettingCommand, + DeleteAttributesCommand, + DeleteCapacityProviderCommand, + DeleteClusterCommand, + DeleteServiceCommand, + DeleteTaskDefinitionsCommand, + DeleteTaskSetCommand, + DeregisterContainerInstanceCommand, + DeregisterTaskDefinitionCommand, + DescribeCapacityProvidersCommand, + DescribeClustersCommand, + DescribeContainerInstancesCommand, + DescribeServiceDeploymentsCommand, + DescribeServiceRevisionsCommand, + DescribeServicesCommand, + DescribeTaskDefinitionCommand, + DescribeTasksCommand, + DescribeTaskSetsCommand, + DiscoverPollEndpointCommand, + ExecuteCommandCommand, + GetTaskProtectionCommand, + ListAccountSettingsCommand, + ListAttributesCommand, + ListClustersCommand, + ListContainerInstancesCommand, + ListServiceDeploymentsCommand, + ListServicesCommand, + ListServicesByNamespaceCommand, + ListTagsForResourceCommand, + ListTaskDefinitionFamiliesCommand, + ListTaskDefinitionsCommand, + ListTasksCommand, + PutAccountSettingCommand, + PutAccountSettingDefaultCommand, + PutAttributesCommand, + PutClusterCapacityProvidersCommand, + RegisterContainerInstanceCommand, + RegisterTaskDefinitionCommand, + RunTaskCommand, + StartTaskCommand, + StopServiceDeploymentCommand, + StopTaskCommand, + SubmitAttachmentStateChangesCommand, + SubmitContainerStateChangeCommand, + SubmitTaskStateChangeCommand, + TagResourceCommand, + UntagResourceCommand, + UpdateCapacityProviderCommand, + UpdateClusterCommand, + UpdateClusterSettingsCommand, + UpdateContainerAgentCommand, + UpdateContainerInstancesStateCommand, + UpdateServiceCommand, + UpdateServicePrimaryTaskSetCommand, + UpdateTaskProtectionCommand, + UpdateTaskSetCommand, +}; +class ECS extends ECSClient { +} +smithyClient.createAggregatedClient(commands, ECS); + +const paginateListAccountSettings = core.createPaginator(ECSClient, ListAccountSettingsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListAttributes = core.createPaginator(ECSClient, ListAttributesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListClusters = core.createPaginator(ECSClient, ListClustersCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListContainerInstances = core.createPaginator(ECSClient, ListContainerInstancesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListServicesByNamespace = core.createPaginator(ECSClient, ListServicesByNamespaceCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListServices = core.createPaginator(ECSClient, ListServicesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListTaskDefinitionFamilies = core.createPaginator(ECSClient, ListTaskDefinitionFamiliesCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListTaskDefinitions = core.createPaginator(ECSClient, ListTaskDefinitionsCommand, "nextToken", "nextToken", "maxResults"); + +const paginateListTasks = core.createPaginator(ECSClient, ListTasksCommand, "nextToken", "nextToken", "maxResults"); + +const checkState$3 = async (client, input) => { + let reason; + try { + const result = await client.send(new DescribeServicesCommand(input)); + reason = result; + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.failures); + const projection_3 = flat_1.map((element_2) => { + return element_2.reason; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "MISSING") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } + } + catch (e) { } + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.services); + const projection_3 = flat_1.map((element_2) => { + return element_2.status; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "INACTIVE") { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + } + catch (e) { } + } + catch (exception) { + reason = exception; + } + return { state: utilWaiter.WaiterState.RETRY, reason }; }; -var NoUpdateAvailableException = class _NoUpdateAvailableException extends ECSServiceException { - static { - __name(this, "NoUpdateAvailableException"); - } - name = "NoUpdateAvailableException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "NoUpdateAvailableException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NoUpdateAvailableException.prototype); - } +const waitForServicesInactive = async (params, input) => { + const serviceDefaults = { minDelay: 15, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); +}; +const waitUntilServicesInactive = async (params, input) => { + const serviceDefaults = { minDelay: 15, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); + return utilWaiter.checkExceptions(result); }; -// src/protocols/Aws_json1_1.ts -var se_CreateCapacityProviderCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("CreateCapacityProvider"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_CreateCapacityProviderCommand"); -var se_CreateClusterCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("CreateCluster"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_CreateClusterCommand"); -var se_CreateServiceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("CreateService"); - let body; - body = JSON.stringify(se_CreateServiceRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_CreateServiceCommand"); -var se_CreateTaskSetCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("CreateTaskSet"); - let body; - body = JSON.stringify(se_CreateTaskSetRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_CreateTaskSetCommand"); -var se_DeleteAccountSettingCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteAccountSetting"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteAccountSettingCommand"); -var se_DeleteAttributesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteAttributes"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteAttributesCommand"); -var se_DeleteCapacityProviderCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteCapacityProvider"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteCapacityProviderCommand"); -var se_DeleteClusterCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteCluster"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteClusterCommand"); -var se_DeleteServiceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteService"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteServiceCommand"); -var se_DeleteTaskDefinitionsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteTaskDefinitions"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteTaskDefinitionsCommand"); -var se_DeleteTaskSetCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeleteTaskSet"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeleteTaskSetCommand"); -var se_DeregisterContainerInstanceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeregisterContainerInstance"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeregisterContainerInstanceCommand"); -var se_DeregisterTaskDefinitionCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DeregisterTaskDefinition"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DeregisterTaskDefinitionCommand"); -var se_DescribeCapacityProvidersCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeCapacityProviders"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeCapacityProvidersCommand"); -var se_DescribeClustersCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeClusters"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeClustersCommand"); -var se_DescribeContainerInstancesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeContainerInstances"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeContainerInstancesCommand"); -var se_DescribeServiceDeploymentsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeServiceDeployments"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeServiceDeploymentsCommand"); -var se_DescribeServiceRevisionsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeServiceRevisions"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeServiceRevisionsCommand"); -var se_DescribeServicesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeServices"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeServicesCommand"); -var se_DescribeTaskDefinitionCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeTaskDefinition"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeTaskDefinitionCommand"); -var se_DescribeTasksCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeTasks"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeTasksCommand"); -var se_DescribeTaskSetsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DescribeTaskSets"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DescribeTaskSetsCommand"); -var se_DiscoverPollEndpointCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("DiscoverPollEndpoint"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DiscoverPollEndpointCommand"); -var se_ExecuteCommandCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ExecuteCommand"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ExecuteCommandCommand"); -var se_GetTaskProtectionCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("GetTaskProtection"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_GetTaskProtectionCommand"); -var se_ListAccountSettingsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListAccountSettings"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListAccountSettingsCommand"); -var se_ListAttributesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListAttributes"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListAttributesCommand"); -var se_ListClustersCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListClusters"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListClustersCommand"); -var se_ListContainerInstancesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListContainerInstances"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListContainerInstancesCommand"); -var se_ListServiceDeploymentsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListServiceDeployments"); - let body; - body = JSON.stringify(se_ListServiceDeploymentsRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListServiceDeploymentsCommand"); -var se_ListServicesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListServices"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListServicesCommand"); -var se_ListServicesByNamespaceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListServicesByNamespace"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListServicesByNamespaceCommand"); -var se_ListTagsForResourceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListTagsForResource"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListTagsForResourceCommand"); -var se_ListTaskDefinitionFamiliesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListTaskDefinitionFamilies"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListTaskDefinitionFamiliesCommand"); -var se_ListTaskDefinitionsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListTaskDefinitions"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListTaskDefinitionsCommand"); -var se_ListTasksCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("ListTasks"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_ListTasksCommand"); -var se_PutAccountSettingCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("PutAccountSetting"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_PutAccountSettingCommand"); -var se_PutAccountSettingDefaultCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("PutAccountSettingDefault"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_PutAccountSettingDefaultCommand"); -var se_PutAttributesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("PutAttributes"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_PutAttributesCommand"); -var se_PutClusterCapacityProvidersCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("PutClusterCapacityProviders"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_PutClusterCapacityProvidersCommand"); -var se_RegisterContainerInstanceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("RegisterContainerInstance"); - let body; - body = JSON.stringify(se_RegisterContainerInstanceRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_RegisterContainerInstanceCommand"); -var se_RegisterTaskDefinitionCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("RegisterTaskDefinition"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_RegisterTaskDefinitionCommand"); -var se_RunTaskCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("RunTask"); - let body; - body = JSON.stringify(se_RunTaskRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_RunTaskCommand"); -var se_StartTaskCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("StartTask"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_StartTaskCommand"); -var se_StopServiceDeploymentCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("StopServiceDeployment"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_StopServiceDeploymentCommand"); -var se_StopTaskCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("StopTask"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_StopTaskCommand"); -var se_SubmitAttachmentStateChangesCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("SubmitAttachmentStateChanges"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_SubmitAttachmentStateChangesCommand"); -var se_SubmitContainerStateChangeCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("SubmitContainerStateChange"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_SubmitContainerStateChangeCommand"); -var se_SubmitTaskStateChangeCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("SubmitTaskStateChange"); - let body; - body = JSON.stringify(se_SubmitTaskStateChangeRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_SubmitTaskStateChangeCommand"); -var se_TagResourceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("TagResource"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_TagResourceCommand"); -var se_UntagResourceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UntagResource"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UntagResourceCommand"); -var se_UpdateCapacityProviderCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateCapacityProvider"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateCapacityProviderCommand"); -var se_UpdateClusterCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateCluster"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateClusterCommand"); -var se_UpdateClusterSettingsCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateClusterSettings"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateClusterSettingsCommand"); -var se_UpdateContainerAgentCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateContainerAgent"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateContainerAgentCommand"); -var se_UpdateContainerInstancesStateCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateContainerInstancesState"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateContainerInstancesStateCommand"); -var se_UpdateServiceCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateService"); - let body; - body = JSON.stringify(se_UpdateServiceRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateServiceCommand"); -var se_UpdateServicePrimaryTaskSetCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateServicePrimaryTaskSet"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateServicePrimaryTaskSetCommand"); -var se_UpdateTaskProtectionCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateTaskProtection"); - let body; - body = JSON.stringify((0, import_smithy_client._json)(input)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateTaskProtectionCommand"); -var se_UpdateTaskSetCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = sharedHeaders("UpdateTaskSet"); - let body; - body = JSON.stringify(se_UpdateTaskSetRequest(input, context)); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_UpdateTaskSetCommand"); -var de_CreateCapacityProviderCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_CreateCapacityProviderCommand"); -var de_CreateClusterCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_CreateClusterCommand"); -var de_CreateServiceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_CreateServiceResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_CreateServiceCommand"); -var de_CreateTaskSetCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_CreateTaskSetResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_CreateTaskSetCommand"); -var de_DeleteAccountSettingCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteAccountSettingCommand"); -var de_DeleteAttributesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteAttributesCommand"); -var de_DeleteCapacityProviderCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteCapacityProviderCommand"); -var de_DeleteClusterCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteClusterCommand"); -var de_DeleteServiceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DeleteServiceResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteServiceCommand"); -var de_DeleteTaskDefinitionsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DeleteTaskDefinitionsResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteTaskDefinitionsCommand"); -var de_DeleteTaskSetCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DeleteTaskSetResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeleteTaskSetCommand"); -var de_DeregisterContainerInstanceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DeregisterContainerInstanceResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeregisterContainerInstanceCommand"); -var de_DeregisterTaskDefinitionCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DeregisterTaskDefinitionResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DeregisterTaskDefinitionCommand"); -var de_DescribeCapacityProvidersCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeCapacityProvidersCommand"); -var de_DescribeClustersCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeClustersCommand"); -var de_DescribeContainerInstancesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeContainerInstancesResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeContainerInstancesCommand"); -var de_DescribeServiceDeploymentsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeServiceDeploymentsResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeServiceDeploymentsCommand"); -var de_DescribeServiceRevisionsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeServiceRevisionsResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeServiceRevisionsCommand"); -var de_DescribeServicesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeServicesResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeServicesCommand"); -var de_DescribeTaskDefinitionCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeTaskDefinitionResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeTaskDefinitionCommand"); -var de_DescribeTasksCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeTasksResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeTasksCommand"); -var de_DescribeTaskSetsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_DescribeTaskSetsResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DescribeTaskSetsCommand"); -var de_DiscoverPollEndpointCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DiscoverPollEndpointCommand"); -var de_ExecuteCommandCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ExecuteCommandCommand"); -var de_GetTaskProtectionCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_GetTaskProtectionResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_GetTaskProtectionCommand"); -var de_ListAccountSettingsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListAccountSettingsCommand"); -var de_ListAttributesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListAttributesCommand"); -var de_ListClustersCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListClustersCommand"); -var de_ListContainerInstancesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListContainerInstancesCommand"); -var de_ListServiceDeploymentsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_ListServiceDeploymentsResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListServiceDeploymentsCommand"); -var de_ListServicesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListServicesCommand"); -var de_ListServicesByNamespaceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListServicesByNamespaceCommand"); -var de_ListTagsForResourceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListTagsForResourceCommand"); -var de_ListTaskDefinitionFamiliesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListTaskDefinitionFamiliesCommand"); -var de_ListTaskDefinitionsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListTaskDefinitionsCommand"); -var de_ListTasksCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_ListTasksCommand"); -var de_PutAccountSettingCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_PutAccountSettingCommand"); -var de_PutAccountSettingDefaultCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_PutAccountSettingDefaultCommand"); -var de_PutAttributesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_PutAttributesCommand"); -var de_PutClusterCapacityProvidersCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_PutClusterCapacityProvidersCommand"); -var de_RegisterContainerInstanceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_RegisterContainerInstanceResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_RegisterContainerInstanceCommand"); -var de_RegisterTaskDefinitionCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_RegisterTaskDefinitionResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_RegisterTaskDefinitionCommand"); -var de_RunTaskCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_RunTaskResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_RunTaskCommand"); -var de_StartTaskCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_StartTaskResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_StartTaskCommand"); -var de_StopServiceDeploymentCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_StopServiceDeploymentCommand"); -var de_StopTaskCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_StopTaskResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_StopTaskCommand"); -var de_SubmitAttachmentStateChangesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_SubmitAttachmentStateChangesCommand"); -var de_SubmitContainerStateChangeCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_SubmitContainerStateChangeCommand"); -var de_SubmitTaskStateChangeCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_SubmitTaskStateChangeCommand"); -var de_TagResourceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_TagResourceCommand"); -var de_UntagResourceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UntagResourceCommand"); -var de_UpdateCapacityProviderCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateCapacityProviderCommand"); -var de_UpdateClusterCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateClusterCommand"); -var de_UpdateClusterSettingsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = (0, import_smithy_client._json)(data); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateClusterSettingsCommand"); -var de_UpdateContainerAgentCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateContainerAgentResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateContainerAgentCommand"); -var de_UpdateContainerInstancesStateCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateContainerInstancesStateResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateContainerInstancesStateCommand"); -var de_UpdateServiceCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateServiceResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateServiceCommand"); -var de_UpdateServicePrimaryTaskSetCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateServicePrimaryTaskSetResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateServicePrimaryTaskSetCommand"); -var de_UpdateTaskProtectionCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateTaskProtectionResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateTaskProtectionCommand"); -var de_UpdateTaskSetCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core2.parseJsonBody)(output.body, context); - let contents = {}; - contents = de_UpdateTaskSetResponse(data, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_UpdateTaskSetCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); - switch (errorCode) { - case "ClientException": - case "com.amazonaws.ecs#ClientException": - throw await de_ClientExceptionRes(parsedOutput, context); - case "InvalidParameterException": - case "com.amazonaws.ecs#InvalidParameterException": - throw await de_InvalidParameterExceptionRes(parsedOutput, context); - case "LimitExceededException": - case "com.amazonaws.ecs#LimitExceededException": - throw await de_LimitExceededExceptionRes(parsedOutput, context); - case "ServerException": - case "com.amazonaws.ecs#ServerException": - throw await de_ServerExceptionRes(parsedOutput, context); - case "UpdateInProgressException": - case "com.amazonaws.ecs#UpdateInProgressException": - throw await de_UpdateInProgressExceptionRes(parsedOutput, context); - case "NamespaceNotFoundException": - case "com.amazonaws.ecs#NamespaceNotFoundException": - throw await de_NamespaceNotFoundExceptionRes(parsedOutput, context); - case "AccessDeniedException": - case "com.amazonaws.ecs#AccessDeniedException": - throw await de_AccessDeniedExceptionRes(parsedOutput, context); - case "ClusterNotFoundException": - case "com.amazonaws.ecs#ClusterNotFoundException": - throw await de_ClusterNotFoundExceptionRes(parsedOutput, context); - case "PlatformTaskDefinitionIncompatibilityException": - case "com.amazonaws.ecs#PlatformTaskDefinitionIncompatibilityException": - throw await de_PlatformTaskDefinitionIncompatibilityExceptionRes(parsedOutput, context); - case "PlatformUnknownException": - case "com.amazonaws.ecs#PlatformUnknownException": - throw await de_PlatformUnknownExceptionRes(parsedOutput, context); - case "UnsupportedFeatureException": - case "com.amazonaws.ecs#UnsupportedFeatureException": - throw await de_UnsupportedFeatureExceptionRes(parsedOutput, context); - case "ServiceNotActiveException": - case "com.amazonaws.ecs#ServiceNotActiveException": - throw await de_ServiceNotActiveExceptionRes(parsedOutput, context); - case "ServiceNotFoundException": - case "com.amazonaws.ecs#ServiceNotFoundException": - throw await de_ServiceNotFoundExceptionRes(parsedOutput, context); - case "TargetNotFoundException": - case "com.amazonaws.ecs#TargetNotFoundException": - throw await de_TargetNotFoundExceptionRes(parsedOutput, context); - case "ClusterContainsContainerInstancesException": - case "com.amazonaws.ecs#ClusterContainsContainerInstancesException": - throw await de_ClusterContainsContainerInstancesExceptionRes(parsedOutput, context); - case "ClusterContainsServicesException": - case "com.amazonaws.ecs#ClusterContainsServicesException": - throw await de_ClusterContainsServicesExceptionRes(parsedOutput, context); - case "ClusterContainsTasksException": - case "com.amazonaws.ecs#ClusterContainsTasksException": - throw await de_ClusterContainsTasksExceptionRes(parsedOutput, context); - case "TaskSetNotFoundException": - case "com.amazonaws.ecs#TaskSetNotFoundException": - throw await de_TaskSetNotFoundExceptionRes(parsedOutput, context); - case "TargetNotConnectedException": - case "com.amazonaws.ecs#TargetNotConnectedException": - throw await de_TargetNotConnectedExceptionRes(parsedOutput, context); - case "ResourceNotFoundException": - case "com.amazonaws.ecs#ResourceNotFoundException": - throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); - case "AttributeLimitExceededException": - case "com.amazonaws.ecs#AttributeLimitExceededException": - throw await de_AttributeLimitExceededExceptionRes(parsedOutput, context); - case "ResourceInUseException": - case "com.amazonaws.ecs#ResourceInUseException": - throw await de_ResourceInUseExceptionRes(parsedOutput, context); - case "BlockedException": - case "com.amazonaws.ecs#BlockedException": - throw await de_BlockedExceptionRes(parsedOutput, context); - case "ConflictException": - case "com.amazonaws.ecs#ConflictException": - throw await de_ConflictExceptionRes(parsedOutput, context); - case "ServiceDeploymentNotFoundException": - case "com.amazonaws.ecs#ServiceDeploymentNotFoundException": - throw await de_ServiceDeploymentNotFoundExceptionRes(parsedOutput, context); - case "MissingVersionException": - case "com.amazonaws.ecs#MissingVersionException": - throw await de_MissingVersionExceptionRes(parsedOutput, context); - case "NoUpdateAvailableException": - case "com.amazonaws.ecs#NoUpdateAvailableException": - throw await de_NoUpdateAvailableExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody, - errorCode - }); - } -}, "de_CommandError"); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_AccessDeniedExceptionRes"); -var de_AttributeLimitExceededExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new AttributeLimitExceededException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_AttributeLimitExceededExceptionRes"); -var de_BlockedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new BlockedException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_BlockedExceptionRes"); -var de_ClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ClientExceptionRes"); -var de_ClusterContainsContainerInstancesExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ClusterContainsContainerInstancesException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ClusterContainsContainerInstancesExceptionRes"); -var de_ClusterContainsServicesExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ClusterContainsServicesException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ClusterContainsServicesExceptionRes"); -var de_ClusterContainsTasksExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ClusterContainsTasksException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ClusterContainsTasksExceptionRes"); -var de_ClusterNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ClusterNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ClusterNotFoundExceptionRes"); -var de_ConflictExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ConflictException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ConflictExceptionRes"); -var de_InvalidParameterExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new InvalidParameterException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_InvalidParameterExceptionRes"); -var de_LimitExceededExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new LimitExceededException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_LimitExceededExceptionRes"); -var de_MissingVersionExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new MissingVersionException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_MissingVersionExceptionRes"); -var de_NamespaceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new NamespaceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_NamespaceNotFoundExceptionRes"); -var de_NoUpdateAvailableExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new NoUpdateAvailableException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_NoUpdateAvailableExceptionRes"); -var de_PlatformTaskDefinitionIncompatibilityExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new PlatformTaskDefinitionIncompatibilityException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_PlatformTaskDefinitionIncompatibilityExceptionRes"); -var de_PlatformUnknownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new PlatformUnknownException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_PlatformUnknownExceptionRes"); -var de_ResourceInUseExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ResourceInUseException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ResourceInUseExceptionRes"); -var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ResourceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ResourceNotFoundExceptionRes"); -var de_ServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ServerExceptionRes"); -var de_ServiceDeploymentNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ServiceDeploymentNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ServiceDeploymentNotFoundExceptionRes"); -var de_ServiceNotActiveExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ServiceNotActiveException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ServiceNotActiveExceptionRes"); -var de_ServiceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new ServiceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ServiceNotFoundExceptionRes"); -var de_TargetNotConnectedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new TargetNotConnectedException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_TargetNotConnectedExceptionRes"); -var de_TargetNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new TargetNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_TargetNotFoundExceptionRes"); -var de_TaskSetNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new TaskSetNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_TaskSetNotFoundExceptionRes"); -var de_UnsupportedFeatureExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new UnsupportedFeatureException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_UnsupportedFeatureExceptionRes"); -var de_UpdateInProgressExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = (0, import_smithy_client._json)(body); - const exception = new UpdateInProgressException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_UpdateInProgressExceptionRes"); -var se_CreatedAt = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - after: /* @__PURE__ */ __name((_) => _.getTime() / 1e3, "after"), - before: /* @__PURE__ */ __name((_) => _.getTime() / 1e3, "before") - }); -}, "se_CreatedAt"); -var se_CreateServiceRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - availabilityZoneRebalancing: [], - capacityProviderStrategy: import_smithy_client._json, - clientToken: [], - cluster: [], - deploymentConfiguration: /* @__PURE__ */ __name((_) => se_DeploymentConfiguration(_, context), "deploymentConfiguration"), - deploymentController: import_smithy_client._json, - desiredCount: [], - enableECSManagedTags: [], - enableExecuteCommand: [], - healthCheckGracePeriodSeconds: [], - launchType: [], - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - placementConstraints: import_smithy_client._json, - placementStrategy: import_smithy_client._json, - platformVersion: [], - propagateTags: [], - role: [], - schedulingStrategy: [], - serviceConnectConfiguration: import_smithy_client._json, - serviceName: [], - serviceRegistries: import_smithy_client._json, - tags: import_smithy_client._json, - taskDefinition: [], - volumeConfigurations: import_smithy_client._json, - vpcLatticeConfigurations: import_smithy_client._json - }); -}, "se_CreateServiceRequest"); -var se_CreateTaskSetRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - capacityProviderStrategy: import_smithy_client._json, - clientToken: [], - cluster: [], - externalId: [], - launchType: [], - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - platformVersion: [], - scale: /* @__PURE__ */ __name((_) => se_Scale(_, context), "scale"), - service: [], - serviceRegistries: import_smithy_client._json, - tags: import_smithy_client._json, - taskDefinition: [] - }); -}, "se_CreateTaskSetRequest"); -var se_DeploymentConfiguration = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - alarms: import_smithy_client._json, - bakeTimeInMinutes: [], - deploymentCircuitBreaker: import_smithy_client._json, - lifecycleHooks: /* @__PURE__ */ __name((_) => se_DeploymentLifecycleHookList(_, context), "lifecycleHooks"), - maximumPercent: [], - minimumHealthyPercent: [], - strategy: [] - }); -}, "se_DeploymentConfiguration"); -var se_DeploymentLifecycleHook = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - hookDetails: /* @__PURE__ */ __name((_) => se_HookDetails(_, context), "hookDetails"), - hookTargetArn: [], - lifecycleStages: import_smithy_client._json, - roleArn: [] - }); -}, "se_DeploymentLifecycleHook"); -var se_DeploymentLifecycleHookList = /* @__PURE__ */ __name((input, context) => { - return input.filter((e) => e != null).map((entry) => { - return se_DeploymentLifecycleHook(entry, context); - }); -}, "se_DeploymentLifecycleHookList"); -var se_HookDetails = /* @__PURE__ */ __name((input, context) => { - return input; -}, "se_HookDetails"); -var se_ListServiceDeploymentsRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - cluster: [], - createdAt: /* @__PURE__ */ __name((_) => se_CreatedAt(_, context), "createdAt"), - maxResults: [], - nextToken: [], - service: [], - status: import_smithy_client._json - }); -}, "se_ListServiceDeploymentsRequest"); -var se_RegisterContainerInstanceRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - attributes: import_smithy_client._json, - cluster: [], - containerInstanceArn: [], - instanceIdentityDocument: [], - instanceIdentityDocumentSignature: [], - platformDevices: import_smithy_client._json, - tags: import_smithy_client._json, - totalResources: /* @__PURE__ */ __name((_) => se_Resources(_, context), "totalResources"), - versionInfo: import_smithy_client._json - }); -}, "se_RegisterContainerInstanceRequest"); -var se_Resource = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - doubleValue: import_smithy_client.serializeFloat, - integerValue: [], - longValue: [], - name: [], - stringSetValue: import_smithy_client._json, - type: [] - }); -}, "se_Resource"); -var se_Resources = /* @__PURE__ */ __name((input, context) => { - return input.filter((e) => e != null).map((entry) => { - return se_Resource(entry, context); - }); -}, "se_Resources"); -var se_RunTaskRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - capacityProviderStrategy: import_smithy_client._json, - clientToken: [true, (_) => _ ?? (0, import_uuid.v4)()], - cluster: [], - count: [], - enableECSManagedTags: [], - enableExecuteCommand: [], - group: [], - launchType: [], - networkConfiguration: import_smithy_client._json, - overrides: import_smithy_client._json, - placementConstraints: import_smithy_client._json, - placementStrategy: import_smithy_client._json, - platformVersion: [], - propagateTags: [], - referenceId: [], - startedBy: [], - tags: import_smithy_client._json, - taskDefinition: [], - volumeConfigurations: import_smithy_client._json - }); -}, "se_RunTaskRequest"); -var se_Scale = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - unit: [], - value: import_smithy_client.serializeFloat - }); -}, "se_Scale"); -var se_SubmitTaskStateChangeRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - attachments: import_smithy_client._json, - cluster: [], - containers: import_smithy_client._json, - executionStoppedAt: /* @__PURE__ */ __name((_) => _.getTime() / 1e3, "executionStoppedAt"), - managedAgents: import_smithy_client._json, - pullStartedAt: /* @__PURE__ */ __name((_) => _.getTime() / 1e3, "pullStartedAt"), - pullStoppedAt: /* @__PURE__ */ __name((_) => _.getTime() / 1e3, "pullStoppedAt"), - reason: [], - status: [], - task: [] - }); -}, "se_SubmitTaskStateChangeRequest"); -var se_UpdateServiceRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - availabilityZoneRebalancing: [], - capacityProviderStrategy: import_smithy_client._json, - cluster: [], - deploymentConfiguration: /* @__PURE__ */ __name((_) => se_DeploymentConfiguration(_, context), "deploymentConfiguration"), - deploymentController: import_smithy_client._json, - desiredCount: [], - enableECSManagedTags: [], - enableExecuteCommand: [], - forceNewDeployment: [], - healthCheckGracePeriodSeconds: [], - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - placementConstraints: import_smithy_client._json, - placementStrategy: import_smithy_client._json, - platformVersion: [], - propagateTags: [], - service: [], - serviceConnectConfiguration: import_smithy_client._json, - serviceRegistries: import_smithy_client._json, - taskDefinition: [], - volumeConfigurations: import_smithy_client._json, - vpcLatticeConfigurations: import_smithy_client._json - }); -}, "se_UpdateServiceRequest"); -var se_UpdateTaskSetRequest = /* @__PURE__ */ __name((input, context) => { - return (0, import_smithy_client.take)(input, { - cluster: [], - scale: /* @__PURE__ */ __name((_) => se_Scale(_, context), "scale"), - service: [], - taskSet: [] - }); -}, "se_UpdateTaskSetRequest"); -var de_Container = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerArn: import_smithy_client.expectString, - cpu: import_smithy_client.expectString, - exitCode: import_smithy_client.expectInt32, - gpuIds: import_smithy_client._json, - healthStatus: import_smithy_client.expectString, - image: import_smithy_client.expectString, - imageDigest: import_smithy_client.expectString, - lastStatus: import_smithy_client.expectString, - managedAgents: /* @__PURE__ */ __name((_) => de_ManagedAgents(_, context), "managedAgents"), - memory: import_smithy_client.expectString, - memoryReservation: import_smithy_client.expectString, - name: import_smithy_client.expectString, - networkBindings: import_smithy_client._json, - networkInterfaces: import_smithy_client._json, - reason: import_smithy_client.expectString, - runtimeId: import_smithy_client.expectString, - taskArn: import_smithy_client.expectString - }); -}, "de_Container"); -var de_ContainerInstance = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - agentConnected: import_smithy_client.expectBoolean, - agentUpdateStatus: import_smithy_client.expectString, - attachments: import_smithy_client._json, - attributes: import_smithy_client._json, - capacityProviderName: import_smithy_client.expectString, - containerInstanceArn: import_smithy_client.expectString, - ec2InstanceId: import_smithy_client.expectString, - healthStatus: /* @__PURE__ */ __name((_) => de_ContainerInstanceHealthStatus(_, context), "healthStatus"), - pendingTasksCount: import_smithy_client.expectInt32, - registeredAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "registeredAt"), - registeredResources: /* @__PURE__ */ __name((_) => de_Resources(_, context), "registeredResources"), - remainingResources: /* @__PURE__ */ __name((_) => de_Resources(_, context), "remainingResources"), - runningTasksCount: import_smithy_client.expectInt32, - status: import_smithy_client.expectString, - statusReason: import_smithy_client.expectString, - tags: import_smithy_client._json, - version: import_smithy_client.expectLong, - versionInfo: import_smithy_client._json - }); -}, "de_ContainerInstance"); -var de_ContainerInstanceHealthStatus = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - details: /* @__PURE__ */ __name((_) => de_InstanceHealthCheckResultList(_, context), "details"), - overallStatus: import_smithy_client.expectString - }); -}, "de_ContainerInstanceHealthStatus"); -var de_ContainerInstances = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ContainerInstance(entry, context); - }); - return retVal; -}, "de_ContainerInstances"); -var de_Containers = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_Container(entry, context); - }); - return retVal; -}, "de_Containers"); -var de_CreateServiceResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - service: /* @__PURE__ */ __name((_) => de_Service(_, context), "service") - }); -}, "de_CreateServiceResponse"); -var de_CreateTaskSetResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - taskSet: /* @__PURE__ */ __name((_) => de_TaskSet(_, context), "taskSet") - }); -}, "de_CreateTaskSetResponse"); -var de_DeleteServiceResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - service: /* @__PURE__ */ __name((_) => de_Service(_, context), "service") - }); -}, "de_DeleteServiceResponse"); -var de_DeleteTaskDefinitionsResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - taskDefinitions: /* @__PURE__ */ __name((_) => de_TaskDefinitionList(_, context), "taskDefinitions") - }); -}, "de_DeleteTaskDefinitionsResponse"); -var de_DeleteTaskSetResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - taskSet: /* @__PURE__ */ __name((_) => de_TaskSet(_, context), "taskSet") - }); -}, "de_DeleteTaskSetResponse"); -var de_Deployment = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - capacityProviderStrategy: import_smithy_client._json, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - desiredCount: import_smithy_client.expectInt32, - failedTasks: import_smithy_client.expectInt32, - fargateEphemeralStorage: import_smithy_client._json, - id: import_smithy_client.expectString, - launchType: import_smithy_client.expectString, - networkConfiguration: import_smithy_client._json, - pendingCount: import_smithy_client.expectInt32, - platformFamily: import_smithy_client.expectString, - platformVersion: import_smithy_client.expectString, - rolloutState: import_smithy_client.expectString, - rolloutStateReason: import_smithy_client.expectString, - runningCount: import_smithy_client.expectInt32, - serviceConnectConfiguration: import_smithy_client._json, - serviceConnectResources: import_smithy_client._json, - status: import_smithy_client.expectString, - taskDefinition: import_smithy_client.expectString, - updatedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "updatedAt"), - volumeConfigurations: import_smithy_client._json, - vpcLatticeConfigurations: import_smithy_client._json - }); -}, "de_Deployment"); -var de_DeploymentConfiguration = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - alarms: import_smithy_client._json, - bakeTimeInMinutes: import_smithy_client.expectInt32, - deploymentCircuitBreaker: import_smithy_client._json, - lifecycleHooks: /* @__PURE__ */ __name((_) => de_DeploymentLifecycleHookList(_, context), "lifecycleHooks"), - maximumPercent: import_smithy_client.expectInt32, - minimumHealthyPercent: import_smithy_client.expectInt32, - strategy: import_smithy_client.expectString - }); -}, "de_DeploymentConfiguration"); -var de_DeploymentLifecycleHook = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - hookDetails: /* @__PURE__ */ __name((_) => de_HookDetails(_, context), "hookDetails"), - hookTargetArn: import_smithy_client.expectString, - lifecycleStages: import_smithy_client._json, - roleArn: import_smithy_client.expectString - }); -}, "de_DeploymentLifecycleHook"); -var de_DeploymentLifecycleHookList = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_DeploymentLifecycleHook(entry, context); - }); - return retVal; -}, "de_DeploymentLifecycleHookList"); -var de_Deployments = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_Deployment(entry, context); - }); - return retVal; -}, "de_Deployments"); -var de_DeregisterContainerInstanceResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerInstance: /* @__PURE__ */ __name((_) => de_ContainerInstance(_, context), "containerInstance") - }); -}, "de_DeregisterContainerInstanceResponse"); -var de_DeregisterTaskDefinitionResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - taskDefinition: /* @__PURE__ */ __name((_) => de_TaskDefinition(_, context), "taskDefinition") - }); -}, "de_DeregisterTaskDefinitionResponse"); -var de_DescribeContainerInstancesResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerInstances: /* @__PURE__ */ __name((_) => de_ContainerInstances(_, context), "containerInstances"), - failures: import_smithy_client._json - }); -}, "de_DescribeContainerInstancesResponse"); -var de_DescribeServiceDeploymentsResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - serviceDeployments: /* @__PURE__ */ __name((_) => de_ServiceDeployments(_, context), "serviceDeployments") - }); -}, "de_DescribeServiceDeploymentsResponse"); -var de_DescribeServiceRevisionsResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - serviceRevisions: /* @__PURE__ */ __name((_) => de_ServiceRevisions(_, context), "serviceRevisions") - }); -}, "de_DescribeServiceRevisionsResponse"); -var de_DescribeServicesResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - services: /* @__PURE__ */ __name((_) => de_Services(_, context), "services") - }); -}, "de_DescribeServicesResponse"); -var de_DescribeTaskDefinitionResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - tags: import_smithy_client._json, - taskDefinition: /* @__PURE__ */ __name((_) => de_TaskDefinition(_, context), "taskDefinition") - }); -}, "de_DescribeTaskDefinitionResponse"); -var de_DescribeTaskSetsResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - taskSets: /* @__PURE__ */ __name((_) => de_TaskSets(_, context), "taskSets") - }); -}, "de_DescribeTaskSetsResponse"); -var de_DescribeTasksResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - tasks: /* @__PURE__ */ __name((_) => de_Tasks(_, context), "tasks") - }); -}, "de_DescribeTasksResponse"); -var de_GetTaskProtectionResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - protectedTasks: /* @__PURE__ */ __name((_) => de_ProtectedTasks(_, context), "protectedTasks") - }); -}, "de_GetTaskProtectionResponse"); -var de_HookDetails = /* @__PURE__ */ __name((output, context) => { - return output; -}, "de_HookDetails"); -var de_InstanceHealthCheckResult = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - lastStatusChange: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "lastStatusChange"), - lastUpdated: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "lastUpdated"), - status: import_smithy_client.expectString, - type: import_smithy_client.expectString - }); -}, "de_InstanceHealthCheckResult"); -var de_InstanceHealthCheckResultList = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_InstanceHealthCheckResult(entry, context); - }); - return retVal; -}, "de_InstanceHealthCheckResultList"); -var de_ListServiceDeploymentsResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - nextToken: import_smithy_client.expectString, - serviceDeployments: /* @__PURE__ */ __name((_) => de_ServiceDeploymentsBrief(_, context), "serviceDeployments") - }); -}, "de_ListServiceDeploymentsResponse"); -var de_ManagedAgent = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - lastStartedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "lastStartedAt"), - lastStatus: import_smithy_client.expectString, - name: import_smithy_client.expectString, - reason: import_smithy_client.expectString - }); -}, "de_ManagedAgent"); -var de_ManagedAgents = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ManagedAgent(entry, context); - }); - return retVal; -}, "de_ManagedAgents"); -var de_ProtectedTask = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - expirationDate: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "expirationDate"), - protectionEnabled: import_smithy_client.expectBoolean, - taskArn: import_smithy_client.expectString - }); -}, "de_ProtectedTask"); -var de_ProtectedTasks = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ProtectedTask(entry, context); - }); - return retVal; -}, "de_ProtectedTasks"); -var de_RegisterContainerInstanceResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerInstance: /* @__PURE__ */ __name((_) => de_ContainerInstance(_, context), "containerInstance") - }); -}, "de_RegisterContainerInstanceResponse"); -var de_RegisterTaskDefinitionResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - tags: import_smithy_client._json, - taskDefinition: /* @__PURE__ */ __name((_) => de_TaskDefinition(_, context), "taskDefinition") - }); -}, "de_RegisterTaskDefinitionResponse"); -var de_Resource = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - doubleValue: import_smithy_client.limitedParseDouble, - integerValue: import_smithy_client.expectInt32, - longValue: import_smithy_client.expectLong, - name: import_smithy_client.expectString, - stringSetValue: import_smithy_client._json, - type: import_smithy_client.expectString - }); -}, "de_Resource"); -var de_Resources = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_Resource(entry, context); - }); - return retVal; -}, "de_Resources"); -var de_Rollback = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - reason: import_smithy_client.expectString, - serviceRevisionArn: import_smithy_client.expectString, - startedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "startedAt") - }); -}, "de_Rollback"); -var de_RunTaskResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - tasks: /* @__PURE__ */ __name((_) => de_Tasks(_, context), "tasks") - }); -}, "de_RunTaskResponse"); -var de_Scale = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - unit: import_smithy_client.expectString, - value: import_smithy_client.limitedParseDouble - }); -}, "de_Scale"); -var de_Service = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - availabilityZoneRebalancing: import_smithy_client.expectString, - capacityProviderStrategy: import_smithy_client._json, - clusterArn: import_smithy_client.expectString, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - createdBy: import_smithy_client.expectString, - deploymentConfiguration: /* @__PURE__ */ __name((_) => de_DeploymentConfiguration(_, context), "deploymentConfiguration"), - deploymentController: import_smithy_client._json, - deployments: /* @__PURE__ */ __name((_) => de_Deployments(_, context), "deployments"), - desiredCount: import_smithy_client.expectInt32, - enableECSManagedTags: import_smithy_client.expectBoolean, - enableExecuteCommand: import_smithy_client.expectBoolean, - events: /* @__PURE__ */ __name((_) => de_ServiceEvents(_, context), "events"), - healthCheckGracePeriodSeconds: import_smithy_client.expectInt32, - launchType: import_smithy_client.expectString, - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - pendingCount: import_smithy_client.expectInt32, - placementConstraints: import_smithy_client._json, - placementStrategy: import_smithy_client._json, - platformFamily: import_smithy_client.expectString, - platformVersion: import_smithy_client.expectString, - propagateTags: import_smithy_client.expectString, - roleArn: import_smithy_client.expectString, - runningCount: import_smithy_client.expectInt32, - schedulingStrategy: import_smithy_client.expectString, - serviceArn: import_smithy_client.expectString, - serviceName: import_smithy_client.expectString, - serviceRegistries: import_smithy_client._json, - status: import_smithy_client.expectString, - tags: import_smithy_client._json, - taskDefinition: import_smithy_client.expectString, - taskSets: /* @__PURE__ */ __name((_) => de_TaskSets(_, context), "taskSets") - }); -}, "de_Service"); -var de_ServiceDeployment = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - alarms: import_smithy_client._json, - clusterArn: import_smithy_client.expectString, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - deploymentCircuitBreaker: import_smithy_client._json, - deploymentConfiguration: /* @__PURE__ */ __name((_) => de_DeploymentConfiguration(_, context), "deploymentConfiguration"), - finishedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "finishedAt"), - lifecycleStage: import_smithy_client.expectString, - rollback: /* @__PURE__ */ __name((_) => de_Rollback(_, context), "rollback"), - serviceArn: import_smithy_client.expectString, - serviceDeploymentArn: import_smithy_client.expectString, - sourceServiceRevisions: import_smithy_client._json, - startedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "startedAt"), - status: import_smithy_client.expectString, - statusReason: import_smithy_client.expectString, - stoppedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "stoppedAt"), - targetServiceRevision: import_smithy_client._json, - updatedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "updatedAt") - }); -}, "de_ServiceDeployment"); -var de_ServiceDeploymentBrief = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - clusterArn: import_smithy_client.expectString, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - finishedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "finishedAt"), - serviceArn: import_smithy_client.expectString, - serviceDeploymentArn: import_smithy_client.expectString, - startedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "startedAt"), - status: import_smithy_client.expectString, - statusReason: import_smithy_client.expectString, - targetServiceRevisionArn: import_smithy_client.expectString - }); -}, "de_ServiceDeploymentBrief"); -var de_ServiceDeployments = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ServiceDeployment(entry, context); - }); - return retVal; -}, "de_ServiceDeployments"); -var de_ServiceDeploymentsBrief = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ServiceDeploymentBrief(entry, context); - }); - return retVal; -}, "de_ServiceDeploymentsBrief"); -var de_ServiceEvent = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - id: import_smithy_client.expectString, - message: import_smithy_client.expectString - }); -}, "de_ServiceEvent"); -var de_ServiceEvents = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ServiceEvent(entry, context); - }); - return retVal; -}, "de_ServiceEvents"); -var de_ServiceRevision = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - capacityProviderStrategy: import_smithy_client._json, - clusterArn: import_smithy_client.expectString, - containerImages: import_smithy_client._json, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - fargateEphemeralStorage: import_smithy_client._json, - guardDutyEnabled: import_smithy_client.expectBoolean, - launchType: import_smithy_client.expectString, - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - platformFamily: import_smithy_client.expectString, - platformVersion: import_smithy_client.expectString, - resolvedConfiguration: import_smithy_client._json, - serviceArn: import_smithy_client.expectString, - serviceConnectConfiguration: import_smithy_client._json, - serviceRegistries: import_smithy_client._json, - serviceRevisionArn: import_smithy_client.expectString, - taskDefinition: import_smithy_client.expectString, - volumeConfigurations: import_smithy_client._json, - vpcLatticeConfigurations: import_smithy_client._json - }); -}, "de_ServiceRevision"); -var de_ServiceRevisions = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_ServiceRevision(entry, context); - }); - return retVal; -}, "de_ServiceRevisions"); -var de_Services = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_Service(entry, context); - }); - return retVal; -}, "de_Services"); -var de_StartTaskResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - tasks: /* @__PURE__ */ __name((_) => de_Tasks(_, context), "tasks") - }); -}, "de_StartTaskResponse"); -var de_StopTaskResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - task: /* @__PURE__ */ __name((_) => de_Task(_, context), "task") - }); -}, "de_StopTaskResponse"); -var de_Task = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - attachments: import_smithy_client._json, - attributes: import_smithy_client._json, - availabilityZone: import_smithy_client.expectString, - capacityProviderName: import_smithy_client.expectString, - clusterArn: import_smithy_client.expectString, - connectivity: import_smithy_client.expectString, - connectivityAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "connectivityAt"), - containerInstanceArn: import_smithy_client.expectString, - containers: /* @__PURE__ */ __name((_) => de_Containers(_, context), "containers"), - cpu: import_smithy_client.expectString, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - desiredStatus: import_smithy_client.expectString, - enableExecuteCommand: import_smithy_client.expectBoolean, - ephemeralStorage: import_smithy_client._json, - executionStoppedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "executionStoppedAt"), - fargateEphemeralStorage: import_smithy_client._json, - group: import_smithy_client.expectString, - healthStatus: import_smithy_client.expectString, - inferenceAccelerators: import_smithy_client._json, - lastStatus: import_smithy_client.expectString, - launchType: import_smithy_client.expectString, - memory: import_smithy_client.expectString, - overrides: import_smithy_client._json, - platformFamily: import_smithy_client.expectString, - platformVersion: import_smithy_client.expectString, - pullStartedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "pullStartedAt"), - pullStoppedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "pullStoppedAt"), - startedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "startedAt"), - startedBy: import_smithy_client.expectString, - stopCode: import_smithy_client.expectString, - stoppedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "stoppedAt"), - stoppedReason: import_smithy_client.expectString, - stoppingAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "stoppingAt"), - tags: import_smithy_client._json, - taskArn: import_smithy_client.expectString, - taskDefinitionArn: import_smithy_client.expectString, - version: import_smithy_client.expectLong - }); -}, "de_Task"); -var de_TaskDefinition = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - compatibilities: import_smithy_client._json, - containerDefinitions: import_smithy_client._json, - cpu: import_smithy_client.expectString, - deregisteredAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "deregisteredAt"), - enableFaultInjection: import_smithy_client.expectBoolean, - ephemeralStorage: import_smithy_client._json, - executionRoleArn: import_smithy_client.expectString, - family: import_smithy_client.expectString, - inferenceAccelerators: import_smithy_client._json, - ipcMode: import_smithy_client.expectString, - memory: import_smithy_client.expectString, - networkMode: import_smithy_client.expectString, - pidMode: import_smithy_client.expectString, - placementConstraints: import_smithy_client._json, - proxyConfiguration: import_smithy_client._json, - registeredAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "registeredAt"), - registeredBy: import_smithy_client.expectString, - requiresAttributes: import_smithy_client._json, - requiresCompatibilities: import_smithy_client._json, - revision: import_smithy_client.expectInt32, - runtimePlatform: import_smithy_client._json, - status: import_smithy_client.expectString, - taskDefinitionArn: import_smithy_client.expectString, - taskRoleArn: import_smithy_client.expectString, - volumes: import_smithy_client._json - }); -}, "de_TaskDefinition"); -var de_TaskDefinitionList = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_TaskDefinition(entry, context); - }); - return retVal; -}, "de_TaskDefinitionList"); -var de_Tasks = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_Task(entry, context); - }); - return retVal; -}, "de_Tasks"); -var de_TaskSet = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - capacityProviderStrategy: import_smithy_client._json, - clusterArn: import_smithy_client.expectString, - computedDesiredCount: import_smithy_client.expectInt32, - createdAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "createdAt"), - externalId: import_smithy_client.expectString, - fargateEphemeralStorage: import_smithy_client._json, - id: import_smithy_client.expectString, - launchType: import_smithy_client.expectString, - loadBalancers: import_smithy_client._json, - networkConfiguration: import_smithy_client._json, - pendingCount: import_smithy_client.expectInt32, - platformFamily: import_smithy_client.expectString, - platformVersion: import_smithy_client.expectString, - runningCount: import_smithy_client.expectInt32, - scale: /* @__PURE__ */ __name((_) => de_Scale(_, context), "scale"), - serviceArn: import_smithy_client.expectString, - serviceRegistries: import_smithy_client._json, - stabilityStatus: import_smithy_client.expectString, - stabilityStatusAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "stabilityStatusAt"), - startedBy: import_smithy_client.expectString, - status: import_smithy_client.expectString, - tags: import_smithy_client._json, - taskDefinition: import_smithy_client.expectString, - taskSetArn: import_smithy_client.expectString, - updatedAt: /* @__PURE__ */ __name((_) => (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseEpochTimestamp)((0, import_smithy_client.expectNumber)(_))), "updatedAt") - }); -}, "de_TaskSet"); -var de_TaskSets = /* @__PURE__ */ __name((output, context) => { - const retVal = (output || []).filter((e) => e != null).map((entry) => { - return de_TaskSet(entry, context); - }); - return retVal; -}, "de_TaskSets"); -var de_UpdateContainerAgentResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerInstance: /* @__PURE__ */ __name((_) => de_ContainerInstance(_, context), "containerInstance") - }); -}, "de_UpdateContainerAgentResponse"); -var de_UpdateContainerInstancesStateResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - containerInstances: /* @__PURE__ */ __name((_) => de_ContainerInstances(_, context), "containerInstances"), - failures: import_smithy_client._json - }); -}, "de_UpdateContainerInstancesStateResponse"); -var de_UpdateServicePrimaryTaskSetResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - taskSet: /* @__PURE__ */ __name((_) => de_TaskSet(_, context), "taskSet") - }); -}, "de_UpdateServicePrimaryTaskSetResponse"); -var de_UpdateServiceResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - service: /* @__PURE__ */ __name((_) => de_Service(_, context), "service") - }); -}, "de_UpdateServiceResponse"); -var de_UpdateTaskProtectionResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - failures: import_smithy_client._json, - protectedTasks: /* @__PURE__ */ __name((_) => de_ProtectedTasks(_, context), "protectedTasks") - }); -}, "de_UpdateTaskProtectionResponse"); -var de_UpdateTaskSetResponse = /* @__PURE__ */ __name((output, context) => { - return (0, import_smithy_client.take)(output, { - taskSet: /* @__PURE__ */ __name((_) => de_TaskSet(_, context), "taskSet") - }); -}, "de_UpdateTaskSetResponse"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(ECSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers - }; - if (resolvedHostname !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -function sharedHeaders(operation) { - return { - "content-type": "application/x-amz-json-1.1", - "x-amz-target": `AmazonEC2ContainerServiceV20141113.${operation}` - }; -} -__name(sharedHeaders, "sharedHeaders"); - -// src/commands/CreateCapacityProviderCommand.ts -var CreateCapacityProviderCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "CreateCapacityProvider", {}).n("ECSClient", "CreateCapacityProviderCommand").f(void 0, void 0).ser(se_CreateCapacityProviderCommand).de(de_CreateCapacityProviderCommand).build() { - static { - __name(this, "CreateCapacityProviderCommand"); - } -}; - -// src/commands/CreateClusterCommand.ts - - - -var CreateClusterCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "CreateCluster", {}).n("ECSClient", "CreateClusterCommand").f(void 0, void 0).ser(se_CreateClusterCommand).de(de_CreateClusterCommand).build() { - static { - __name(this, "CreateClusterCommand"); - } -}; - -// src/commands/CreateServiceCommand.ts - - - -var CreateServiceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "CreateService", {}).n("ECSClient", "CreateServiceCommand").f(void 0, void 0).ser(se_CreateServiceCommand).de(de_CreateServiceCommand).build() { - static { - __name(this, "CreateServiceCommand"); - } -}; - -// src/commands/CreateTaskSetCommand.ts - - - -var CreateTaskSetCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "CreateTaskSet", {}).n("ECSClient", "CreateTaskSetCommand").f(void 0, void 0).ser(se_CreateTaskSetCommand).de(de_CreateTaskSetCommand).build() { - static { - __name(this, "CreateTaskSetCommand"); - } -}; - -// src/commands/DeleteAccountSettingCommand.ts - - - -var DeleteAccountSettingCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteAccountSetting", {}).n("ECSClient", "DeleteAccountSettingCommand").f(void 0, void 0).ser(se_DeleteAccountSettingCommand).de(de_DeleteAccountSettingCommand).build() { - static { - __name(this, "DeleteAccountSettingCommand"); - } -}; - -// src/commands/DeleteAttributesCommand.ts - - - -var DeleteAttributesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteAttributes", {}).n("ECSClient", "DeleteAttributesCommand").f(void 0, void 0).ser(se_DeleteAttributesCommand).de(de_DeleteAttributesCommand).build() { - static { - __name(this, "DeleteAttributesCommand"); - } -}; - -// src/commands/DeleteCapacityProviderCommand.ts - - - -var DeleteCapacityProviderCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteCapacityProvider", {}).n("ECSClient", "DeleteCapacityProviderCommand").f(void 0, void 0).ser(se_DeleteCapacityProviderCommand).de(de_DeleteCapacityProviderCommand).build() { - static { - __name(this, "DeleteCapacityProviderCommand"); - } -}; - -// src/commands/DeleteClusterCommand.ts - - - -var DeleteClusterCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteCluster", {}).n("ECSClient", "DeleteClusterCommand").f(void 0, void 0).ser(se_DeleteClusterCommand).de(de_DeleteClusterCommand).build() { - static { - __name(this, "DeleteClusterCommand"); - } -}; - -// src/commands/DeleteServiceCommand.ts - - - -var DeleteServiceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteService", {}).n("ECSClient", "DeleteServiceCommand").f(void 0, void 0).ser(se_DeleteServiceCommand).de(de_DeleteServiceCommand).build() { - static { - __name(this, "DeleteServiceCommand"); - } -}; - -// src/commands/DeleteTaskDefinitionsCommand.ts - - - -var DeleteTaskDefinitionsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteTaskDefinitions", {}).n("ECSClient", "DeleteTaskDefinitionsCommand").f(void 0, void 0).ser(se_DeleteTaskDefinitionsCommand).de(de_DeleteTaskDefinitionsCommand).build() { - static { - __name(this, "DeleteTaskDefinitionsCommand"); - } -}; - -// src/commands/DeleteTaskSetCommand.ts - - - -var DeleteTaskSetCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeleteTaskSet", {}).n("ECSClient", "DeleteTaskSetCommand").f(void 0, void 0).ser(se_DeleteTaskSetCommand).de(de_DeleteTaskSetCommand).build() { - static { - __name(this, "DeleteTaskSetCommand"); - } -}; - -// src/commands/DeregisterContainerInstanceCommand.ts - - - -var DeregisterContainerInstanceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeregisterContainerInstance", {}).n("ECSClient", "DeregisterContainerInstanceCommand").f(void 0, void 0).ser(se_DeregisterContainerInstanceCommand).de(de_DeregisterContainerInstanceCommand).build() { - static { - __name(this, "DeregisterContainerInstanceCommand"); - } -}; - -// src/commands/DeregisterTaskDefinitionCommand.ts - - - -var DeregisterTaskDefinitionCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DeregisterTaskDefinition", {}).n("ECSClient", "DeregisterTaskDefinitionCommand").f(void 0, void 0).ser(se_DeregisterTaskDefinitionCommand).de(de_DeregisterTaskDefinitionCommand).build() { - static { - __name(this, "DeregisterTaskDefinitionCommand"); - } -}; - -// src/commands/DescribeCapacityProvidersCommand.ts - - - -var DescribeCapacityProvidersCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeCapacityProviders", {}).n("ECSClient", "DescribeCapacityProvidersCommand").f(void 0, void 0).ser(se_DescribeCapacityProvidersCommand).de(de_DescribeCapacityProvidersCommand).build() { - static { - __name(this, "DescribeCapacityProvidersCommand"); - } -}; - -// src/commands/DescribeClustersCommand.ts - - - -var DescribeClustersCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeClusters", {}).n("ECSClient", "DescribeClustersCommand").f(void 0, void 0).ser(se_DescribeClustersCommand).de(de_DescribeClustersCommand).build() { - static { - __name(this, "DescribeClustersCommand"); - } -}; - -// src/commands/DescribeContainerInstancesCommand.ts - - - -var DescribeContainerInstancesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeContainerInstances", {}).n("ECSClient", "DescribeContainerInstancesCommand").f(void 0, void 0).ser(se_DescribeContainerInstancesCommand).de(de_DescribeContainerInstancesCommand).build() { - static { - __name(this, "DescribeContainerInstancesCommand"); - } -}; - -// src/commands/DescribeServiceDeploymentsCommand.ts - - - -var DescribeServiceDeploymentsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeServiceDeployments", {}).n("ECSClient", "DescribeServiceDeploymentsCommand").f(void 0, void 0).ser(se_DescribeServiceDeploymentsCommand).de(de_DescribeServiceDeploymentsCommand).build() { - static { - __name(this, "DescribeServiceDeploymentsCommand"); - } -}; - -// src/commands/DescribeServiceRevisionsCommand.ts - - - -var DescribeServiceRevisionsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeServiceRevisions", {}).n("ECSClient", "DescribeServiceRevisionsCommand").f(void 0, void 0).ser(se_DescribeServiceRevisionsCommand).de(de_DescribeServiceRevisionsCommand).build() { - static { - __name(this, "DescribeServiceRevisionsCommand"); - } -}; - -// src/commands/DescribeServicesCommand.ts - - - -var DescribeServicesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeServices", {}).n("ECSClient", "DescribeServicesCommand").f(void 0, void 0).ser(se_DescribeServicesCommand).de(de_DescribeServicesCommand).build() { - static { - __name(this, "DescribeServicesCommand"); - } -}; - -// src/commands/DescribeTaskDefinitionCommand.ts - - - -var DescribeTaskDefinitionCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeTaskDefinition", {}).n("ECSClient", "DescribeTaskDefinitionCommand").f(void 0, void 0).ser(se_DescribeTaskDefinitionCommand).de(de_DescribeTaskDefinitionCommand).build() { - static { - __name(this, "DescribeTaskDefinitionCommand"); - } -}; - -// src/commands/DescribeTasksCommand.ts - - - -var DescribeTasksCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeTasks", {}).n("ECSClient", "DescribeTasksCommand").f(void 0, void 0).ser(se_DescribeTasksCommand).de(de_DescribeTasksCommand).build() { - static { - __name(this, "DescribeTasksCommand"); - } -}; - -// src/commands/DescribeTaskSetsCommand.ts - - - -var DescribeTaskSetsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DescribeTaskSets", {}).n("ECSClient", "DescribeTaskSetsCommand").f(void 0, void 0).ser(se_DescribeTaskSetsCommand).de(de_DescribeTaskSetsCommand).build() { - static { - __name(this, "DescribeTaskSetsCommand"); - } -}; - -// src/commands/DiscoverPollEndpointCommand.ts - - - -var DiscoverPollEndpointCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "DiscoverPollEndpoint", {}).n("ECSClient", "DiscoverPollEndpointCommand").f(void 0, void 0).ser(se_DiscoverPollEndpointCommand).de(de_DiscoverPollEndpointCommand).build() { - static { - __name(this, "DiscoverPollEndpointCommand"); - } -}; - -// src/commands/ExecuteCommandCommand.ts - - - -var ExecuteCommandCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ExecuteCommand", {}).n("ECSClient", "ExecuteCommandCommand").f(void 0, ExecuteCommandResponseFilterSensitiveLog).ser(se_ExecuteCommandCommand).de(de_ExecuteCommandCommand).build() { - static { - __name(this, "ExecuteCommandCommand"); - } -}; - -// src/commands/GetTaskProtectionCommand.ts - - - -var GetTaskProtectionCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "GetTaskProtection", {}).n("ECSClient", "GetTaskProtectionCommand").f(void 0, void 0).ser(se_GetTaskProtectionCommand).de(de_GetTaskProtectionCommand).build() { - static { - __name(this, "GetTaskProtectionCommand"); - } -}; - -// src/commands/ListAccountSettingsCommand.ts - - - -var ListAccountSettingsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListAccountSettings", {}).n("ECSClient", "ListAccountSettingsCommand").f(void 0, void 0).ser(se_ListAccountSettingsCommand).de(de_ListAccountSettingsCommand).build() { - static { - __name(this, "ListAccountSettingsCommand"); - } -}; - -// src/commands/ListAttributesCommand.ts - - - -var ListAttributesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListAttributes", {}).n("ECSClient", "ListAttributesCommand").f(void 0, void 0).ser(se_ListAttributesCommand).de(de_ListAttributesCommand).build() { - static { - __name(this, "ListAttributesCommand"); - } -}; - -// src/commands/ListClustersCommand.ts - - - -var ListClustersCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListClusters", {}).n("ECSClient", "ListClustersCommand").f(void 0, void 0).ser(se_ListClustersCommand).de(de_ListClustersCommand).build() { - static { - __name(this, "ListClustersCommand"); - } -}; - -// src/commands/ListContainerInstancesCommand.ts - - - -var ListContainerInstancesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListContainerInstances", {}).n("ECSClient", "ListContainerInstancesCommand").f(void 0, void 0).ser(se_ListContainerInstancesCommand).de(de_ListContainerInstancesCommand).build() { - static { - __name(this, "ListContainerInstancesCommand"); - } -}; - -// src/commands/ListServiceDeploymentsCommand.ts - - - -var ListServiceDeploymentsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListServiceDeployments", {}).n("ECSClient", "ListServiceDeploymentsCommand").f(void 0, void 0).ser(se_ListServiceDeploymentsCommand).de(de_ListServiceDeploymentsCommand).build() { - static { - __name(this, "ListServiceDeploymentsCommand"); - } -}; - -// src/commands/ListServicesByNamespaceCommand.ts - - - -var ListServicesByNamespaceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListServicesByNamespace", {}).n("ECSClient", "ListServicesByNamespaceCommand").f(void 0, void 0).ser(se_ListServicesByNamespaceCommand).de(de_ListServicesByNamespaceCommand).build() { - static { - __name(this, "ListServicesByNamespaceCommand"); - } -}; - -// src/commands/ListServicesCommand.ts - - - -var ListServicesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListServices", {}).n("ECSClient", "ListServicesCommand").f(void 0, void 0).ser(se_ListServicesCommand).de(de_ListServicesCommand).build() { - static { - __name(this, "ListServicesCommand"); - } -}; - -// src/commands/ListTagsForResourceCommand.ts - - - -var ListTagsForResourceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListTagsForResource", {}).n("ECSClient", "ListTagsForResourceCommand").f(void 0, void 0).ser(se_ListTagsForResourceCommand).de(de_ListTagsForResourceCommand).build() { - static { - __name(this, "ListTagsForResourceCommand"); - } -}; - -// src/commands/ListTaskDefinitionFamiliesCommand.ts - - - -var ListTaskDefinitionFamiliesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListTaskDefinitionFamilies", {}).n("ECSClient", "ListTaskDefinitionFamiliesCommand").f(void 0, void 0).ser(se_ListTaskDefinitionFamiliesCommand).de(de_ListTaskDefinitionFamiliesCommand).build() { - static { - __name(this, "ListTaskDefinitionFamiliesCommand"); - } -}; - -// src/commands/ListTaskDefinitionsCommand.ts - - - -var ListTaskDefinitionsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListTaskDefinitions", {}).n("ECSClient", "ListTaskDefinitionsCommand").f(void 0, void 0).ser(se_ListTaskDefinitionsCommand).de(de_ListTaskDefinitionsCommand).build() { - static { - __name(this, "ListTaskDefinitionsCommand"); - } -}; - -// src/commands/ListTasksCommand.ts - - - -var ListTasksCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "ListTasks", {}).n("ECSClient", "ListTasksCommand").f(void 0, void 0).ser(se_ListTasksCommand).de(de_ListTasksCommand).build() { - static { - __name(this, "ListTasksCommand"); - } -}; - -// src/commands/PutAccountSettingCommand.ts - - - -var PutAccountSettingCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "PutAccountSetting", {}).n("ECSClient", "PutAccountSettingCommand").f(void 0, void 0).ser(se_PutAccountSettingCommand).de(de_PutAccountSettingCommand).build() { - static { - __name(this, "PutAccountSettingCommand"); - } -}; - -// src/commands/PutAccountSettingDefaultCommand.ts - - - -var PutAccountSettingDefaultCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "PutAccountSettingDefault", {}).n("ECSClient", "PutAccountSettingDefaultCommand").f(void 0, void 0).ser(se_PutAccountSettingDefaultCommand).de(de_PutAccountSettingDefaultCommand).build() { - static { - __name(this, "PutAccountSettingDefaultCommand"); - } -}; - -// src/commands/PutAttributesCommand.ts - - - -var PutAttributesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "PutAttributes", {}).n("ECSClient", "PutAttributesCommand").f(void 0, void 0).ser(se_PutAttributesCommand).de(de_PutAttributesCommand).build() { - static { - __name(this, "PutAttributesCommand"); - } -}; - -// src/commands/PutClusterCapacityProvidersCommand.ts - - - -var PutClusterCapacityProvidersCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "PutClusterCapacityProviders", {}).n("ECSClient", "PutClusterCapacityProvidersCommand").f(void 0, void 0).ser(se_PutClusterCapacityProvidersCommand).de(de_PutClusterCapacityProvidersCommand).build() { - static { - __name(this, "PutClusterCapacityProvidersCommand"); - } -}; - -// src/commands/RegisterContainerInstanceCommand.ts - - - -var RegisterContainerInstanceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "RegisterContainerInstance", {}).n("ECSClient", "RegisterContainerInstanceCommand").f(void 0, void 0).ser(se_RegisterContainerInstanceCommand).de(de_RegisterContainerInstanceCommand).build() { - static { - __name(this, "RegisterContainerInstanceCommand"); - } -}; - -// src/commands/RegisterTaskDefinitionCommand.ts - - - -var RegisterTaskDefinitionCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "RegisterTaskDefinition", {}).n("ECSClient", "RegisterTaskDefinitionCommand").f(void 0, void 0).ser(se_RegisterTaskDefinitionCommand).de(de_RegisterTaskDefinitionCommand).build() { - static { - __name(this, "RegisterTaskDefinitionCommand"); - } -}; - -// src/commands/RunTaskCommand.ts - - - -var RunTaskCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "RunTask", {}).n("ECSClient", "RunTaskCommand").f(void 0, void 0).ser(se_RunTaskCommand).de(de_RunTaskCommand).build() { - static { - __name(this, "RunTaskCommand"); - } -}; - -// src/commands/StartTaskCommand.ts - - - -var StartTaskCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "StartTask", {}).n("ECSClient", "StartTaskCommand").f(void 0, void 0).ser(se_StartTaskCommand).de(de_StartTaskCommand).build() { - static { - __name(this, "StartTaskCommand"); - } -}; - -// src/commands/StopServiceDeploymentCommand.ts - - - -var StopServiceDeploymentCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "StopServiceDeployment", {}).n("ECSClient", "StopServiceDeploymentCommand").f(void 0, void 0).ser(se_StopServiceDeploymentCommand).de(de_StopServiceDeploymentCommand).build() { - static { - __name(this, "StopServiceDeploymentCommand"); - } -}; - -// src/commands/StopTaskCommand.ts - - - -var StopTaskCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "StopTask", {}).n("ECSClient", "StopTaskCommand").f(void 0, void 0).ser(se_StopTaskCommand).de(de_StopTaskCommand).build() { - static { - __name(this, "StopTaskCommand"); - } -}; - -// src/commands/SubmitAttachmentStateChangesCommand.ts - - - -var SubmitAttachmentStateChangesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "SubmitAttachmentStateChanges", {}).n("ECSClient", "SubmitAttachmentStateChangesCommand").f(void 0, void 0).ser(se_SubmitAttachmentStateChangesCommand).de(de_SubmitAttachmentStateChangesCommand).build() { - static { - __name(this, "SubmitAttachmentStateChangesCommand"); - } -}; - -// src/commands/SubmitContainerStateChangeCommand.ts - - - -var SubmitContainerStateChangeCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "SubmitContainerStateChange", {}).n("ECSClient", "SubmitContainerStateChangeCommand").f(void 0, void 0).ser(se_SubmitContainerStateChangeCommand).de(de_SubmitContainerStateChangeCommand).build() { - static { - __name(this, "SubmitContainerStateChangeCommand"); - } -}; - -// src/commands/SubmitTaskStateChangeCommand.ts - - - -var SubmitTaskStateChangeCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "SubmitTaskStateChange", {}).n("ECSClient", "SubmitTaskStateChangeCommand").f(void 0, void 0).ser(se_SubmitTaskStateChangeCommand).de(de_SubmitTaskStateChangeCommand).build() { - static { - __name(this, "SubmitTaskStateChangeCommand"); - } -}; - -// src/commands/TagResourceCommand.ts - - - -var TagResourceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "TagResource", {}).n("ECSClient", "TagResourceCommand").f(void 0, void 0).ser(se_TagResourceCommand).de(de_TagResourceCommand).build() { - static { - __name(this, "TagResourceCommand"); - } -}; - -// src/commands/UntagResourceCommand.ts - - - -var UntagResourceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UntagResource", {}).n("ECSClient", "UntagResourceCommand").f(void 0, void 0).ser(se_UntagResourceCommand).de(de_UntagResourceCommand).build() { - static { - __name(this, "UntagResourceCommand"); - } -}; - -// src/commands/UpdateCapacityProviderCommand.ts - - - -var UpdateCapacityProviderCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateCapacityProvider", {}).n("ECSClient", "UpdateCapacityProviderCommand").f(void 0, void 0).ser(se_UpdateCapacityProviderCommand).de(de_UpdateCapacityProviderCommand).build() { - static { - __name(this, "UpdateCapacityProviderCommand"); - } -}; - -// src/commands/UpdateClusterCommand.ts - - - -var UpdateClusterCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateCluster", {}).n("ECSClient", "UpdateClusterCommand").f(void 0, void 0).ser(se_UpdateClusterCommand).de(de_UpdateClusterCommand).build() { - static { - __name(this, "UpdateClusterCommand"); - } -}; - -// src/commands/UpdateClusterSettingsCommand.ts - - - -var UpdateClusterSettingsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateClusterSettings", {}).n("ECSClient", "UpdateClusterSettingsCommand").f(void 0, void 0).ser(se_UpdateClusterSettingsCommand).de(de_UpdateClusterSettingsCommand).build() { - static { - __name(this, "UpdateClusterSettingsCommand"); - } -}; - -// src/commands/UpdateContainerAgentCommand.ts - - - -var UpdateContainerAgentCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateContainerAgent", {}).n("ECSClient", "UpdateContainerAgentCommand").f(void 0, void 0).ser(se_UpdateContainerAgentCommand).de(de_UpdateContainerAgentCommand).build() { - static { - __name(this, "UpdateContainerAgentCommand"); - } -}; - -// src/commands/UpdateContainerInstancesStateCommand.ts - - - -var UpdateContainerInstancesStateCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateContainerInstancesState", {}).n("ECSClient", "UpdateContainerInstancesStateCommand").f(void 0, void 0).ser(se_UpdateContainerInstancesStateCommand).de(de_UpdateContainerInstancesStateCommand).build() { - static { - __name(this, "UpdateContainerInstancesStateCommand"); - } -}; - -// src/commands/UpdateServiceCommand.ts - - - -var UpdateServiceCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateService", {}).n("ECSClient", "UpdateServiceCommand").f(void 0, void 0).ser(se_UpdateServiceCommand).de(de_UpdateServiceCommand).build() { - static { - __name(this, "UpdateServiceCommand"); - } -}; - -// src/commands/UpdateServicePrimaryTaskSetCommand.ts - - - -var UpdateServicePrimaryTaskSetCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateServicePrimaryTaskSet", {}).n("ECSClient", "UpdateServicePrimaryTaskSetCommand").f(void 0, void 0).ser(se_UpdateServicePrimaryTaskSetCommand).de(de_UpdateServicePrimaryTaskSetCommand).build() { - static { - __name(this, "UpdateServicePrimaryTaskSetCommand"); - } -}; - -// src/commands/UpdateTaskProtectionCommand.ts - - - -var UpdateTaskProtectionCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateTaskProtection", {}).n("ECSClient", "UpdateTaskProtectionCommand").f(void 0, void 0).ser(se_UpdateTaskProtectionCommand).de(de_UpdateTaskProtectionCommand).build() { - static { - __name(this, "UpdateTaskProtectionCommand"); - } -}; - -// src/commands/UpdateTaskSetCommand.ts - - - -var UpdateTaskSetCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AmazonEC2ContainerServiceV20141113", "UpdateTaskSet", {}).n("ECSClient", "UpdateTaskSetCommand").f(void 0, void 0).ser(se_UpdateTaskSetCommand).de(de_UpdateTaskSetCommand).build() { - static { - __name(this, "UpdateTaskSetCommand"); - } -}; - -// src/ECS.ts -var commands = { - CreateCapacityProviderCommand, - CreateClusterCommand, - CreateServiceCommand, - CreateTaskSetCommand, - DeleteAccountSettingCommand, - DeleteAttributesCommand, - DeleteCapacityProviderCommand, - DeleteClusterCommand, - DeleteServiceCommand, - DeleteTaskDefinitionsCommand, - DeleteTaskSetCommand, - DeregisterContainerInstanceCommand, - DeregisterTaskDefinitionCommand, - DescribeCapacityProvidersCommand, - DescribeClustersCommand, - DescribeContainerInstancesCommand, - DescribeServiceDeploymentsCommand, - DescribeServiceRevisionsCommand, - DescribeServicesCommand, - DescribeTaskDefinitionCommand, - DescribeTasksCommand, - DescribeTaskSetsCommand, - DiscoverPollEndpointCommand, - ExecuteCommandCommand, - GetTaskProtectionCommand, - ListAccountSettingsCommand, - ListAttributesCommand, - ListClustersCommand, - ListContainerInstancesCommand, - ListServiceDeploymentsCommand, - ListServicesCommand, - ListServicesByNamespaceCommand, - ListTagsForResourceCommand, - ListTaskDefinitionFamiliesCommand, - ListTaskDefinitionsCommand, - ListTasksCommand, - PutAccountSettingCommand, - PutAccountSettingDefaultCommand, - PutAttributesCommand, - PutClusterCapacityProvidersCommand, - RegisterContainerInstanceCommand, - RegisterTaskDefinitionCommand, - RunTaskCommand, - StartTaskCommand, - StopServiceDeploymentCommand, - StopTaskCommand, - SubmitAttachmentStateChangesCommand, - SubmitContainerStateChangeCommand, - SubmitTaskStateChangeCommand, - TagResourceCommand, - UntagResourceCommand, - UpdateCapacityProviderCommand, - UpdateClusterCommand, - UpdateClusterSettingsCommand, - UpdateContainerAgentCommand, - UpdateContainerInstancesStateCommand, - UpdateServiceCommand, - UpdateServicePrimaryTaskSetCommand, - UpdateTaskProtectionCommand, - UpdateTaskSetCommand -}; -var ECS = class extends ECSClient { - static { - __name(this, "ECS"); - } -}; -(0, import_smithy_client.createAggregatedClient)(commands, ECS); - -// src/pagination/ListAccountSettingsPaginator.ts - -var paginateListAccountSettings = (0, import_core.createPaginator)(ECSClient, ListAccountSettingsCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListAttributesPaginator.ts - -var paginateListAttributes = (0, import_core.createPaginator)(ECSClient, ListAttributesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListClustersPaginator.ts - -var paginateListClusters = (0, import_core.createPaginator)(ECSClient, ListClustersCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListContainerInstancesPaginator.ts - -var paginateListContainerInstances = (0, import_core.createPaginator)(ECSClient, ListContainerInstancesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListServicesByNamespacePaginator.ts - -var paginateListServicesByNamespace = (0, import_core.createPaginator)(ECSClient, ListServicesByNamespaceCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListServicesPaginator.ts - -var paginateListServices = (0, import_core.createPaginator)(ECSClient, ListServicesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListTaskDefinitionFamiliesPaginator.ts - -var paginateListTaskDefinitionFamilies = (0, import_core.createPaginator)(ECSClient, ListTaskDefinitionFamiliesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListTaskDefinitionsPaginator.ts - -var paginateListTaskDefinitions = (0, import_core.createPaginator)(ECSClient, ListTaskDefinitionsCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListTasksPaginator.ts - -var paginateListTasks = (0, import_core.createPaginator)(ECSClient, ListTasksCommand, "nextToken", "nextToken", "maxResults"); - -// src/waiters/waitForServicesInactive.ts -var import_util_waiter = __nccwpck_require__(95290); -var checkState = /* @__PURE__ */ __name(async (client, input) => { - let reason; - try { - const result = await client.send(new DescribeServicesCommand(input)); - reason = result; - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.failures); - const projection_3 = flat_1.map((element_2) => { - return element_2.reason; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "MISSING") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.services); - const projection_3 = flat_1.map((element_2) => { - return element_2.status; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "INACTIVE") { - return { state: import_util_waiter.WaiterState.SUCCESS, reason }; - } - } - } catch (e) { - } - } catch (exception) { - reason = exception; - } - return { state: import_util_waiter.WaiterState.RETRY, reason }; -}, "checkState"); -var waitForServicesInactive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 15, maxDelay: 120 }; - return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState); -}, "waitForServicesInactive"); -var waitUntilServicesInactive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 15, maxDelay: 120 }; - const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState); - return (0, import_util_waiter.checkExceptions)(result); -}, "waitUntilServicesInactive"); - -// src/waiters/waitForServicesStable.ts - -var checkState2 = /* @__PURE__ */ __name(async (client, input) => { - let reason; - try { - const result = await client.send(new DescribeServicesCommand(input)); - reason = result; - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.failures); - const projection_3 = flat_1.map((element_2) => { - return element_2.reason; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "MISSING") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.services); - const projection_3 = flat_1.map((element_2) => { - return element_2.status; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "DRAINING") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.services); - const projection_3 = flat_1.map((element_2) => { - return element_2.status; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "INACTIVE") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const filterRes_2 = result.services.filter((element_1) => { - return !(element_1.deployments.length == 1 && element_1.runningCount == element_1.desiredCount); - }); - return filterRes_2.length == 0; - }, "returnComparator"); - if (returnComparator() == true) { - return { state: import_util_waiter.WaiterState.SUCCESS, reason }; - } - } catch (e) { - } - } catch (exception) { - reason = exception; - } - return { state: import_util_waiter.WaiterState.RETRY, reason }; -}, "checkState"); -var waitForServicesStable = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 15, maxDelay: 120 }; - return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState2); -}, "waitForServicesStable"); -var waitUntilServicesStable = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 15, maxDelay: 120 }; - const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState2); - return (0, import_util_waiter.checkExceptions)(result); -}, "waitUntilServicesStable"); - -// src/waiters/waitForTasksRunning.ts - -var checkState3 = /* @__PURE__ */ __name(async (client, input) => { - let reason; - try { - const result = await client.send(new DescribeTasksCommand(input)); - reason = result; - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.tasks); - const projection_3 = flat_1.map((element_2) => { - return element_2.lastStatus; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "STOPPED") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.failures); - const projection_3 = flat_1.map((element_2) => { - return element_2.reason; - }); - return projection_3; - }, "returnComparator"); - for (const anyStringEq_4 of returnComparator()) { - if (anyStringEq_4 == "MISSING") { - return { state: import_util_waiter.WaiterState.FAILURE, reason }; - } - } - } catch (e) { - } - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.tasks); - const projection_3 = flat_1.map((element_2) => { - return element_2.lastStatus; - }); - return projection_3; - }, "returnComparator"); - let allStringEq_5 = returnComparator().length > 0; - for (const element_4 of returnComparator()) { - allStringEq_5 = allStringEq_5 && element_4 == "RUNNING"; - } - if (allStringEq_5) { - return { state: import_util_waiter.WaiterState.SUCCESS, reason }; - } - } catch (e) { - } - } catch (exception) { - reason = exception; - } - return { state: import_util_waiter.WaiterState.RETRY, reason }; -}, "checkState"); -var waitForTasksRunning = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 6, maxDelay: 120 }; - return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState3); -}, "waitForTasksRunning"); -var waitUntilTasksRunning = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 6, maxDelay: 120 }; - const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState3); - return (0, import_util_waiter.checkExceptions)(result); -}, "waitUntilTasksRunning"); - -// src/waiters/waitForTasksStopped.ts - -var checkState4 = /* @__PURE__ */ __name(async (client, input) => { - let reason; - try { - const result = await client.send(new DescribeTasksCommand(input)); - reason = result; - try { - const returnComparator = /* @__PURE__ */ __name(() => { - const flat_1 = [].concat(...result.tasks); - const projection_3 = flat_1.map((element_2) => { - return element_2.lastStatus; - }); - return projection_3; - }, "returnComparator"); - let allStringEq_5 = returnComparator().length > 0; - for (const element_4 of returnComparator()) { - allStringEq_5 = allStringEq_5 && element_4 == "STOPPED"; - } - if (allStringEq_5) { - return { state: import_util_waiter.WaiterState.SUCCESS, reason }; - } - } catch (e) { - } - } catch (exception) { - reason = exception; - } - return { state: import_util_waiter.WaiterState.RETRY, reason }; -}, "checkState"); -var waitForTasksStopped = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 6, maxDelay: 120 }; - return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState4); -}, "waitForTasksStopped"); -var waitUntilTasksStopped = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 6, maxDelay: 120 }; - const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState4); - return (0, import_util_waiter.checkExceptions)(result); -}, "waitUntilTasksStopped"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 41142: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(51194)); -const core_1 = __nccwpck_require__(91446); -const credential_provider_node_1 = __nccwpck_require__(60395); -const util_user_agent_node_1 = __nccwpck_require__(9082); -const config_resolver_1 = __nccwpck_require__(39316); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(61814); -const node_http_handler_1 = __nccwpck_require__(95493); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(31519); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 31519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(91446); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(85792); -const util_base64_1 = __nccwpck_require__(82763); -const util_utf8_1 = __nccwpck_require__(85339); -const httpAuthSchemeProvider_1 = __nccwpck_require__(1367); -const endpointResolver_1 = __nccwpck_require__(6161); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2014-11-13", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultECSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "ECS", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 50111: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(91446); -const util_middleware_1 = __nccwpck_require__(30954); -const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccountRoles": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccounts": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "Logout": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 57321: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(16158); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(79170); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 79170: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 43628: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, - GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, - GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, - InvalidRequestException: () => InvalidRequestException, - ListAccountRolesCommand: () => ListAccountRolesCommand, - ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, - ListAccountsCommand: () => ListAccountsCommand, - ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, - LogoutCommand: () => LogoutCommand, - LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, - ResourceNotFoundException: () => ResourceNotFoundException, - RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, - SSO: () => SSO, - SSOClient: () => SSOClient, - SSOServiceException: () => SSOServiceException, - TooManyRequestsException: () => TooManyRequestsException, - UnauthorizedException: () => UnauthorizedException, - __Client: () => import_smithy_client.Client, - paginateListAccountRoles: () => paginateListAccountRoles, - paginateListAccounts: () => paginateListAccounts -}); -module.exports = __toCommonJS(index_exports); - -// src/SSOClient.ts -var import_middleware_host_header = __nccwpck_require__(25164); -var import_middleware_logger = __nccwpck_require__(65832); -var import_middleware_recursion_detection = __nccwpck_require__(39870); -var import_middleware_user_agent = __nccwpck_require__(70997); -var import_config_resolver = __nccwpck_require__(39316); -var import_core = __nccwpck_require__(22744); -var import_middleware_content_length = __nccwpck_require__(47212); -var import_middleware_endpoint = __nccwpck_require__(88205); -var import_middleware_retry = __nccwpck_require__(19618); - -var import_httpAuthSchemeProvider = __nccwpck_require__(50111); - -// src/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/SSOClient.ts -var import_runtimeConfig = __nccwpck_require__(88766); - -// src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(26521); -var import_protocol_http = __nccwpck_require__(13494); -var import_smithy_client = __nccwpck_require__(61411); - -// src/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/SSOClient.ts -var SSOClient = class extends import_smithy_client.Client { - static { - __name(this, "SSOClient"); - } - /** - * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/SSO.ts - - -// src/commands/GetRoleCredentialsCommand.ts - -var import_middleware_serde = __nccwpck_require__(58305); - - -// src/models/models_0.ts - - -// src/models/SSOServiceException.ts - -var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "SSOServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOServiceException.prototype); - } -}; - -// src/models/models_0.ts -var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - } -}; -var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { - static { - __name(this, "ResourceNotFoundException"); - } - name = "ResourceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } -}; -var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { - static { - __name(this, "TooManyRequestsException"); - } - name = "TooManyRequestsException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsException.prototype); - } -}; -var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { - static { - __name(this, "UnauthorizedException"); - } - name = "UnauthorizedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedException.prototype); - } -}; -var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "GetRoleCredentialsRequestFilterSensitiveLog"); -var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, - ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } -}), "RoleCredentialsFilterSensitiveLog"); -var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } -}), "GetRoleCredentialsResponseFilterSensitiveLog"); -var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountRolesRequestFilterSensitiveLog"); -var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountsRequestFilterSensitiveLog"); -var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "LogoutRequestFilterSensitiveLog"); - -// src/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(91446); - - -var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/federation/credentials"); - const query = (0, import_smithy_client.map)({ - [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_GetRoleCredentialsCommand"); -var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/roles"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountRolesCommand"); -var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/accounts"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountsCommand"); -var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/logout"); - let body; - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_LogoutCommand"); -var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - roleCredentials: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_GetRoleCredentialsCommand"); -var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - nextToken: import_smithy_client.expectString, - roleList: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountRolesCommand"); -var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - accountList: import_smithy_client._json, - nextToken: import_smithy_client.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountsCommand"); -var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - await (0, import_smithy_client.collectBody)(output.body, context); - return contents; -}, "de_LogoutCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); - switch (errorCode) { - case "InvalidRequestException": - case "com.amazonaws.sso#InvalidRequestException": - throw await de_InvalidRequestExceptionRes(parsedOutput, context); - case "ResourceNotFoundException": - case "com.amazonaws.sso#ResourceNotFoundException": - throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); - case "TooManyRequestsException": - case "com.amazonaws.sso#TooManyRequestsException": - throw await de_TooManyRequestsExceptionRes(parsedOutput, context); - case "UnauthorizedException": - case "com.amazonaws.sso#UnauthorizedException": - throw await de_UnauthorizedExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody, - errorCode - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new ResourceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_ResourceNotFoundExceptionRes"); -var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new TooManyRequestsException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_TooManyRequestsExceptionRes"); -var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); -var _aI = "accountId"; -var _aT = "accessToken"; -var _ai = "account_id"; -var _mR = "maxResults"; -var _mr = "max_result"; -var _nT = "nextToken"; -var _nt = "next_token"; -var _rN = "roleName"; -var _rn = "role_name"; -var _xasbt = "x-amz-sso_bearer_token"; - -// src/commands/GetRoleCredentialsCommand.ts -var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { - static { - __name(this, "GetRoleCredentialsCommand"); - } -}; - -// src/commands/ListAccountRolesCommand.ts - - - -var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { - static { - __name(this, "ListAccountRolesCommand"); - } -}; - -// src/commands/ListAccountsCommand.ts - - - -var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { - static { - __name(this, "ListAccountsCommand"); - } -}; - -// src/commands/LogoutCommand.ts - - - -var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { - static { - __name(this, "LogoutCommand"); - } -}; - -// src/SSO.ts -var commands = { - GetRoleCredentialsCommand, - ListAccountRolesCommand, - ListAccountsCommand, - LogoutCommand -}; -var SSO = class extends SSOClient { - static { - __name(this, "SSO"); - } -}; -(0, import_smithy_client.createAggregatedClient)(commands, SSO); - -// src/pagination/ListAccountRolesPaginator.ts - -var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListAccountsPaginator.ts - -var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 88766: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(36948)); -const core_1 = __nccwpck_require__(91446); -const util_user_agent_node_1 = __nccwpck_require__(9082); -const config_resolver_1 = __nccwpck_require__(39316); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(61814); -const node_http_handler_1 = __nccwpck_require__(95493); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(35831); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 35831: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(91446); -const core_2 = __nccwpck_require__(22744); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(85792); -const util_base64_1 = __nccwpck_require__(82763); -const util_utf8_1 = __nccwpck_require__(85339); -const httpAuthSchemeProvider_1 = __nccwpck_require__(50111); -const endpointResolver_1 = __nccwpck_require__(57321); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 91446: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(61860); -tslib_1.__exportStar(__nccwpck_require__(17582), exports); -tslib_1.__exportStar(__nccwpck_require__(7321), exports); -tslib_1.__exportStar(__nccwpck_require__(91914), exports); - - -/***/ }), - -/***/ 17582: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/client/index.ts -var index_exports = {}; -__export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false -}; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI` - ); - } -}, "emitWarningIfUnsupportedVersion"); - -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} -__name(setCredentialFeature, "setCredentialFeature"); - -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} -__name(setFeature, "setFeature"); - -// src/submodules/client/setTokenFeature.ts -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} -__name(setTokenFeature, "setTokenFeature"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 7321: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/httpAuthSchemes/index.ts -var index_exports = {}; -__export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(13494); - -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts -var import_protocol_http = __nccwpck_require__(13494); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); - -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); - -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); - -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { - static { - __name(this, "AwsSdkSigV4Signer"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -}; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(13494); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - static { - __name(this, "AwsSdkSigV4ASigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName - }); - return signedRequest; - } -}; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), - /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), - /** - * Default auth scheme preference if not specified in environment or config - */ - default: [] -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(22744); -var import_property_provider = __nccwpck_require__(1104); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(17582); -var import_core2 = __nccwpck_require__(22744); -var import_signature_v4 = __nccwpck_require__(75118); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; - } - } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); - } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 91914: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/protocols/index.ts -var index_exports = {}; -__export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts -var import_cbor = __nccwpck_require__(91467); -var import_schema2 = __nccwpck_require__(41320); - -// src/submodules/protocols/ProtocolLib.ts -var import_schema = __nccwpck_require__(41320); -var import_util_body_length_browser = __nccwpck_require__(84916); -var ProtocolLib = class { - static { - __name(this, "ProtocolLib"); - } - /** - * @param body - to be inspected. - * @param serdeContext - this is a subset type but in practice is the client.config having a property called bodyLengthChecker. - * - * @returns content-length value for the body if possible. - * @throws Error and should be caught and handled if not possible to determine length. - */ - calculateContentLength(body, serdeContext) { - const bodyLengthCalculator = serdeContext?.bodyLengthChecker ?? import_util_body_length_browser.calculateBodyLength; - return String(bodyLengthCalculator(body)); - } - /** - * This is only for REST protocols. - * - * @param defaultContentType - of the protocol. - * @param inputSchema - schema for which to determine content type. - * - * @returns content-type header value or undefined when not applicable. - */ - resolveRestContentType(defaultContentType, inputSchema) { - const members = inputSchema.getMemberSchemas(); - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - return mediaType; - } else if (httpPayloadMember.isStringSchema()) { - return "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - return "application/octet-stream"; - } else { - return defaultContentType; - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - const noPrefixHeaders = httpPrefixHeaders === void 0; - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; - }); - if (hasBody) { - return defaultContentType; - } - } - } - /** - * Shared code for finding error schema or throwing an unmodeled base error. - * @returns error schema and error metadata. - * - * @throws ServiceBaseException or generic Error if no error schema could be found. - */ - async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { - let namespace = defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $response: response, - $fault: response.statusCode < 500 ? "client" : "server" - }; - const registry = import_schema.TypeRegistry.for(namespace); - try { - const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); - return { errorSchema, errorMetadata }; - } catch (e) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; - } - const baseExceptionSchema = import_schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); - } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); - } - } - /** - * Reads the x-amzn-query-error header for awsQuery compatibility. - * - * @param output - values that will be assigned to an error object. - * @param response - from which to read awsQueryError headers. - */ - setQueryCompatError(output, response) { - const queryErrorHeader = response.headers?.["x-amzn-query-error"]; - if (output !== void 0 && queryErrorHeader != null) { - const [Code, Type] = queryErrorHeader.split(";"); - const entries = Object.entries(output); - const Error2 = { - Code, - Type - }; - Object.assign(output, Error2); - for (const [k, v] of entries) { - Error2[k] = v; - } - delete Error2.__type; - output.Error = Error2; - } - } - /** - * Assigns Error, Type, Code from the awsQuery error object to the output error object. - * @param queryCompatErrorData - query compat error object. - * @param errorData - canonical error object returned to the caller. - */ - queryCompatOutput(queryCompatErrorData, errorData) { - if (queryCompatErrorData.Error) { - errorData.Error = queryCompatErrorData.Error; - } - if (queryCompatErrorData.Type) { - errorData.Type = queryCompatErrorData.Type; - } - if (queryCompatErrorData.Code) { - errorData.Code = queryCompatErrorData.Code; - } - } -}; - -// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts -var AwsSmithyRpcV2CborProtocol = class extends import_cbor.SmithyRpcV2CborProtocol { - static { - __name(this, "AwsSmithyRpcV2CborProtocol"); - } - awsQueryCompatible; - mixin = new ProtocolLib(); - constructor({ - defaultNamespace, - awsQueryCompatible - }) { - super({ defaultNamespace }); - this.awsQueryCompatible = !!awsQueryCompatible; - } - /** - * @override - */ - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - return request; - } - /** - * @override - */ - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorName = (0, import_cbor.loadSmithyRpcV2CborErrorCode)(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorName, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema2.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } -}; - -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "number" || typeof val === "bigint") { - const warning = new Error(`Received number ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - if (typeof val === "boolean") { - const warning = new Error(`Received boolean ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - return val; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "number") { - } - if (typeof val === "string") { - const lowercase = val.toLowerCase(); - if (val !== "" && lowercase !== "false" && lowercase !== "true") { - const warning = new Error(`Received string "${val}" where a boolean was expected.`); - warning.name = "Warning"; - console.warn(warning); - } - return val !== "" && lowercase !== "false"; - } - return val; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "boolean") { - } - if (typeof val === "string") { - const num = Number(val); - if (num.toString() !== val) { - const warning = new Error(`Received string "${val}" where a number was expected.`); - warning.name = "Warning"; - console.warn(warning); - return val; - } - return num; - } - return val; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols3 = __nccwpck_require__(86752); -var import_schema5 = __nccwpck_require__(41320); - -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); - } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -}; - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_protocols = __nccwpck_require__(86752); -var import_schema3 = __nccwpck_require__(41320); -var import_serde2 = __nccwpck_require__(98520); -var import_util_base64 = __nccwpck_require__(82763); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(98520); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; -} -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(61411); -var import_util_utf8 = __nccwpck_require__(85339); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_util_utf8.toUtf8)(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } - } -}, "loadRestJsonErrorCode"); - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeDeserializer"); - } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema3.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema() && value != null) { - const format = (0, import_protocols.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema3.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema3.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - const untyped = value; - if (untyped.type === "bigDecimal" && "string" in untyped) { - return new import_serde2.NumericValue(untyped.string, untyped.type); - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof import_serde2.NumericValue) { - out[k] = v; - } else { - out[k] = this._read(ns, v); - } - } - return out; - } else { - return structuredClone(value); - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_protocols2 = __nccwpck_require__(86752); -var import_schema4 = __nccwpck_require__(41320); -var import_serde4 = __nccwpck_require__(98520); -var import_util_base642 = __nccwpck_require__(82763); - -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(98520); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { - static { - __name(this, "JsonReplacer"); - } - /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. - */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; - } - /** - * Replaces placeholder keys with their true values. - */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeSerializer"); - } - buffer; - rootSchema; - write(schema, value) { - this.rootSchema = import_schema4.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); - } - /** - * @internal - */ - writeDiscriminatedDocument(schema, value) { - this.write(schema, value); - if (typeof this.buffer === "object") { - this.buffer.__type = import_schema4.NormalizedSchema.of(schema).getName(true); - } - } - flush() { - const { rootSchema } = this; - this.rootSchema = void 0; - if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema4.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string") || ns.isDocumentSchema() && value instanceof Uint8Array) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - return (0, import_util_base642.toBase64)(value); - } - return this.serdeContext?.base64Encoder(value); - } - if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { - const format = (0, import_protocols2.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema4.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return (0, import_serde4.generateIdempotencyToken)(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde4.LazyJsonString.from(value); - } - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof import_serde4.NumericValue) { - out[k] = v; - } else { - out[k] = this._write(ns, v); - } - } - return out; - } else { - return structuredClone(value); - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonCodec"); - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -}; - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols3.RpcProtocol { - static { - __name(this, "AwsJsonRpcProtocol"); - } - serializer; - deserializer; - serviceTarget; - codec; - mixin = new ProtocolLib(); - awsQueryCompatible; - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace - }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - this.awsQueryCompatible = !!awsQueryCompatible; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${import_schema5.NormalizedSchema.of(operationSchema).getName()}` - }); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - if ((0, import_schema5.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema5.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } -}; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_0Protocol"); - } - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } - /** - * @override - */ - getDefaultContentType() { - return "application/x-amz-json-1.0"; - } -}; - -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_1Protocol"); - } - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } - /** - * @override - */ - getDefaultContentType() { - return "application/x-amz-json-1.1"; - } -}; - -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols4 = __nccwpck_require__(86752); -var import_schema6 = __nccwpck_require__(41320); -var AwsRestJsonProtocol = class extends import_protocols4.HttpBindingProtocol { - static { - __name(this, "AwsRestJsonProtocol"); - } - serializer; - deserializer; - codec; - mixin = new ProtocolLib(); - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols4.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols4.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema6.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema6.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } - /** - * @override - */ - getDefaultContentType() { - return "application/json"; - } -}; - -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(61411); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols7 = __nccwpck_require__(86752); -var import_schema9 = __nccwpck_require__(41320); - -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols5 = __nccwpck_require__(86752); -var import_schema7 = __nccwpck_require__(41320); -var import_smithy_client3 = __nccwpck_require__(61411); -var import_util_utf82 = __nccwpck_require__(85339); -var import_fast_xml_parser = __nccwpck_require__(50591); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols5.FromStringShapeDeserializer(settings); - } - static { - __name(this, "XmlShapeDeserializer"); - } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. - */ - read(schema, bytes, key) { - const ns = import_schema7.NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = import_schema7.NormalizedSchema.of(_schema); - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer2 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer2.push(this.readSchema(listValue, v)); - } - } - return buffer2; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - if (value2 != null || sparse) { - buffer[key] = this.readSchema(memberNs, value2); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - parseXml(xml) { - if (xml.length) { - const parser = new import_fast_xml_parser.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(xml, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); - } - return {}; - } -}; - -// src/submodules/protocols/query/QueryShapeSerializer.ts -var import_protocols6 = __nccwpck_require__(86752); -var import_schema8 = __nccwpck_require__(41320); -var import_serde5 = __nccwpck_require__(98520); -var import_smithy_client4 = __nccwpck_require__(61411); -var import_util_base643 = __nccwpck_require__(82763); -var QueryShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "QueryShapeSerializer"); - } - buffer; - write(schema, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; - } - const ns = import_schema8.NormalizedSchema.of(schema); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue((0, import_serde5.generateIdempotencyToken)()); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof import_serde5.NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = (0, import_protocols6.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: - this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); - break; - case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.writeValue(String(value.getTime() / 1e3)); - break; - } - } - } else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); - } - return key; - } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${(0, import_protocols6.extendedEncodeURIComponent)(key)}=`; - } - writeValue(value) { - this.buffer += (0, import_protocols6.extendedEncodeURIComponent)(value); - } -}; - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var AwsQueryProtocol = class extends import_protocols7.RpcProtocol { - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); - } - static { - __name(this, "AwsQueryProtocol"); - } - serializer; - deserializer; - mixin = new ProtocolLib(); - getShapeId() { - return "aws.protocols#awsQuery"; - } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` - }); - if ((0, import_schema9.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - const action = operationSchema.name.split("#")[1] ?? operationSchema.name; - request.body = `Action=${action}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema9.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await (0, import_protocols7.collectBody)(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema9.SCHEMA.DOCUMENT, bytes2)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; - const bytes = await (0, import_protocols7.collectBody)(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; - } - /** - * EC2 Query overrides this. - */ - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - const errorData = this.loadQueryError(dataObject); - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - errorData, - metadata, - (registry, errorName) => registry.find( - (schema) => import_schema9.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName - ) - ); - const ns = import_schema9.NormalizedSchema.of(errorSchema); - const message = this.loadQueryErrorMessage(dataObject); - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorData[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } - /** - * The variations in the error and error message locations are attributed to - * divergence between AWS Query and EC2 Query behavior. - */ - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== void 0) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; - } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; - } - /** - * @override - */ - getDefaultContentType() { - return "application/x-www-form-urlencoded"; - } -}; - -// src/submodules/protocols/query/AwsEc2QueryProtocol.ts -var AwsEc2QueryProtocol = class extends AwsQueryProtocol { - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false - }; - Object.assign(this.serializer.settings, ec2Settings); - } - static { - __name(this, "AwsEc2QueryProtocol"); - } - /** - * EC2 Query reads XResponse.XResult instead of XResponse directly. - */ - useNestedResult() { - return false; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var import_protocols9 = __nccwpck_require__(86752); -var import_schema11 = __nccwpck_require__(41320); - -// src/submodules/protocols/xml/parseXmlBody.ts -var import_smithy_client5 = __nccwpck_require__(61411); -var import_fast_xml_parser2 = __nccwpck_require__(50591); -var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - const parser = new import_fast_xml_parser2.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(encoded, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return (0, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); - } - return {}; -}), "parseXmlBody"); -var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}, "parseXmlErrorBody"); -var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data?.Error?.Code !== void 0) { - return data.Error.Code; - } - if (data?.Code !== void 0) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadRestXmlErrorCode"); - -// src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(2344); -var import_protocols8 = __nccwpck_require__(86752); -var import_schema10 = __nccwpck_require__(41320); -var import_serde6 = __nccwpck_require__(98520); -var import_smithy_client6 = __nccwpck_require__(61411); -var import_util_base644 = __nccwpck_require__(82763); -var XmlShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlShapeSerializer"); - } - stringBuffer; - byteBuffer; - buffer; - write(schema, value) { - const ns = import_schema10.NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base644.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( - true - )}.` - ); - } - const structXmlNode = import_xml_builder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute( - memberSchema.getMergedTraits().xmlName ?? memberName, - this.writeSimple(memberSchema, val) - ); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - return structXmlNode; - } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` - ); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = /* @__PURE__ */ __name((container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode( - struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") - ); - } else { - const listItemNode = import_xml_builder.XmlNode.of( - flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" - ); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }, "writeItem"); - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } - } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` - ); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { - const keyNode = import_xml_builder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }, "addKeyValue"); - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = import_schema10.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base644.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const format = (0, import_protocols8.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema10.SCHEMA.TIMESTAMP_DATE_TIME: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema10.SCHEMA.TIMESTAMP_HTTP_DATE: - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - case import_schema10.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof import_serde6.NumericValue) { - return value.string; - } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error( - "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." - ); - } else { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( - true - )}` - ); - } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { - nodeContents = (0, import_serde6.generateIdempotencyToken)(); - } else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = import_schema10.NormalizedSchema.of(_schema); - const content = new import_xml_builder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } -}; - -// src/submodules/protocols/xml/XmlCodec.ts -var XmlCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlCodec"); - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var AwsRestXmlProtocol = class extends import_protocols9.HttpBindingProtocol { - static { - __name(this, "AwsRestXmlProtocol"); - } - codec; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema11.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace - }; - this.codec = new XmlCodec(settings); - this.serializer = new import_protocols9.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols9.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema11.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - if (request.body) { - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema11.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } - /** - * @override - */ - getDefaultContentType() { - return "application/xml"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 56104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, - ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, - ENV_EXPIRATION: () => ENV_EXPIRATION, - ENV_KEY: () => ENV_KEY, - ENV_SECRET: () => ENV_SECRET, - ENV_SESSION: () => ENV_SESSION, - fromEnv: () => fromEnv -}); -module.exports = __toCommonJS(index_exports); - -// src/fromEnv.ts -var import_client = __nccwpck_require__(17582); -var import_property_provider = __nccwpck_require__(1104); -var ENV_KEY = "AWS_ACCESS_KEY_ID"; -var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; -var ENV_SESSION = "AWS_SESSION_TOKEN"; -var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; -var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; -var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; -var fromEnv = /* @__PURE__ */ __name((init) => async () => { - init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...sessionToken && { sessionToken }, - ...expiry && { expiration: new Date(expiry) }, - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; - } - throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); -}, "fromEnv"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 24815: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkUrl = void 0; -const property_provider_1 = __nccwpck_require__(1104); -const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; -const LOOPBACK_CIDR_IPv6 = "::1/128"; -const ECS_CONTAINER_HOST = "169.254.170.2"; -const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; -const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; -const checkUrl = (url, logger) => { - if (url.protocol === "https:") { - return; - } - if (url.hostname === ECS_CONTAINER_HOST || - url.hostname === EKS_CONTAINER_HOST_IPv4 || - url.hostname === EKS_CONTAINER_HOST_IPv6) { - return; - } - if (url.hostname.includes("[")) { - if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; - } - } - else { - if (url.hostname === "localhost") { - return; - } - const ipComponents = url.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && - inRange(ipComponents[1]) && - inRange(ipComponents[2]) && - inRange(ipComponents[3]) && - ipComponents.length === 4) { - return; - } - } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); -}; -exports.checkUrl = checkUrl; - - -/***/ }), - -/***/ 57030: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -const tslib_1 = __nccwpck_require__(61860); -const client_1 = __nccwpck_require__(17582); -const node_http_handler_1 = __nccwpck_require__(95493); -const property_provider_1 = __nccwpck_require__(1104); -const promises_1 = tslib_1.__importDefault(__nccwpck_require__(91943)); -const checkUrl_1 = __nccwpck_require__(24815); -const requestHelpers_1 = __nccwpck_require__(94604); -const retry_wrapper_1 = __nccwpck_require__(98692); -const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; -const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn - ? console.warn - : options.logger.warn.bind(options.logger); - if (relative && full) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } - else if (relative) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; - } - else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); - } - const url = new URL(host); - (0, checkUrl_1.checkUrl)(url, options.logger); - const requestHandler = new node_http_handler_1.NodeHttpHandler({ - requestTimeout: options.timeout ?? 1000, - connectionTimeout: options.timeout ?? 1000, - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url); - if (token) { - request.headers.Authorization = token; - } - else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); - } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); - } - catch (e) { - throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); - } - }, options.maxRetries ?? 3, options.timeout ?? 1000); -}; -exports.fromHttp = fromHttp; - - -/***/ }), - -/***/ 94604: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createGetRequest = createGetRequest; -exports.getCredentials = getCredentials; -const property_provider_1 = __nccwpck_require__(1104); -const protocol_http_1 = __nccwpck_require__(13494); -const smithy_client_1 = __nccwpck_require__(61411); -const util_stream_1 = __nccwpck_require__(71914); -function createGetRequest(url) { - return new protocol_http_1.HttpRequest({ - protocol: url.protocol, - hostname: url.hostname, - port: Number(url.port), - path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { - acc[k] = v; - return acc; - }, {}), - fragment: url.hash, - }); -} -async function getCredentials(response, logger) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || - typeof parsed.SecretAccessKey !== "string" || - typeof parsed.Token !== "string" || - typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + - "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), - }; - } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } - catch (e) { } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { - Code: parsedBody.Code, - Message: parsedBody.Message, - }); - } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); -} - - -/***/ }), - -/***/ 98692: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.retryWrapper = void 0; -const retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i = 0; i < maxRetries; ++i) { - try { - return await toRetry(); - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, delayMs)); - } - } - return await toRetry(); - }; -}; -exports.retryWrapper = retryWrapper; - - -/***/ }), - -/***/ 60795: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -var fromHttp_1 = __nccwpck_require__(57030); -Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); - - -/***/ }), - -/***/ 26163: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromIni: () => fromIni -}); -module.exports = __toCommonJS(index_exports); - -// src/fromIni.ts - - -// src/resolveProfileData.ts - - -// src/resolveAssumeRoleCredentials.ts - - -var import_shared_ini_file_loader = __nccwpck_require__(93438); - -// src/resolveCredentialSource.ts -var import_client = __nccwpck_require__(17582); -var import_property_provider = __nccwpck_require__(1104); -var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { - const sourceProvidersMap = { - EcsContainer: /* @__PURE__ */ __name(async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60795))); - const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, "EcsContainer"), - Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, "Ec2InstanceMetadata"), - Environment: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(56104))); - return async () => fromEnv(options)().then(setNamedProvider); - }, "Environment") - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } else { - throw new import_property_provider.CredentialsProviderError( - `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, - { logger } - ); - } -}, "resolveCredentialSource"); -var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); - -// src/resolveAssumeRoleCredentials.ts -var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { - return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); -}, "isAssumeRoleProfile"); -var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); - } - return withSourceProfile; -}, "isAssumeRoleWithSourceProfile"); -var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); - } - return withProviderProfile; -}, "isCredentialSourceProfile"); -var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(31058))); - options.roleAssumer = getDefaultRoleAssumer( - { - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region - } - }, - options.clientPlugins - ); - } - if (source_profile && source_profile in visitedProfiles) { - throw new import_property_provider.CredentialsProviderError( - `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), - { logger: options.logger } - ); - } - options.logger?.debug( - `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` - ); - const sourceCredsProvider = source_profile ? resolveProfileData( - source_profile, - profiles, - options, - { - ...visitedProfiles, - [source_profile]: true - }, - isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) - ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new import_property_provider.CredentialsProviderError( - `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, - { logger: options.logger, tryNextLink: false } - ); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") - ); - } -}, "resolveAssumeRoleCredentials"); -var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { - return !section.role_arn && !!section.credential_source; -}, "isCredentialSourceWithoutRoleArn"); - -// src/resolveProcessCredentials.ts - -var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); -var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(15630))).then( - ({ fromProcess }) => fromProcess({ - ...options, - profile - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) -), "resolveProcessCredentials"); - -// src/resolveSsoCredentials.ts - -var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8212))); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig - })().then((creds) => { - if (profileData.sso_session) { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } else { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); - } - }); -}, "resolveSsoCredentials"); -var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); - -// src/resolveStaticCredentials.ts - -var isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); -var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, - ...profile.aws_account_id && { accountId: profile.aws_account_id } - }; - return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); -}, "resolveStaticCredentials"); - -// src/resolveWebIdentityCredentials.ts - -var isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile"); -var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(47654))).then( - ({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) -), "resolveWebIdentityCredentials"); - -// src/resolveProfileData.ts -var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); - } - if (isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isWebIdentityProfile(data)) { - return resolveWebIdentityCredentials(data, options); - } - if (isProcessProfile(data)) { - return resolveProcessCredentials(options, profileName); - } - if (isSsoProfile(data)) { - return await resolveSsoCredentials(profileName, data, options); - } - throw new import_property_provider.CredentialsProviderError( - `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, - { logger: options.logger } - ); -}, "resolveProfileData"); - -// src/fromIni.ts -var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProfileData( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: _init.profile ?? callerClientConfig?.profile - }), - profiles, - init - ); -}, "fromIni"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 60395: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, - credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, - defaultProvider: () => defaultProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultProvider.ts -var import_credential_provider_env = __nccwpck_require__(56104); - -var import_shared_ini_file_loader = __nccwpck_require__(93438); - -// src/remoteProvider.ts -var import_property_provider = __nccwpck_require__(1104); -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var remoteProvider = /* @__PURE__ */ __name(async (init) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60795))); - return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); - }; - } - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init); -}, "remoteProvider"); - -// src/defaultProvider.ts -var multipleCredentialSourceWarningEmitted = false; -var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - async () => { - const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn; - warnFn( - `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -` - ); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init.logger, - tryNextLink: true - }); - } - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return (0, import_credential_provider_env.fromEnv)(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new import_property_provider.CredentialsProviderError( - "Skipping SSO provider in default chain (inputs do not include SSO fields).", - { logger: init.logger } - ); - } - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8212))); - return fromSSO(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(26163))); - return fromIni(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(15630))); - return fromProcess(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(47654))); - return fromTokenFile(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger - }); - } - ), - credentialsTreatedAsExpired, - credentialsWillNeedRefresh -), "defaultProvider"); -var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); -var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 15630: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromProcess: () => fromProcess -}); -module.exports = __toCommonJS(index_exports); - -// src/fromProcess.ts -var import_shared_ini_file_loader = __nccwpck_require__(93438); - -// src/resolveProcessCredentials.ts -var import_property_provider = __nccwpck_require__(1104); -var import_child_process = __nccwpck_require__(35317); -var import_util = __nccwpck_require__(39023); - -// src/getValidatedProcessCredentials.ts -var import_client = __nccwpck_require__(17582); -var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } - } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...data.SessionToken && { sessionToken: data.SessionToken }, - ...data.Expiration && { expiration: new Date(data.Expiration) }, - ...data.CredentialScope && { credentialScope: data.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; -}, "getValidatedProcessCredentials"); - -// src/resolveProcessCredentials.ts -var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = (0, import_util.promisify)(import_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; - try { - data = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data, profiles); - } catch (error) { - throw new import_property_provider.CredentialsProviderError(error.message, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger - }); - } -}, "resolveProcessCredentials"); - -// src/fromProcess.ts -var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProcessCredentials( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }), - profiles, - init.logger - ); -}, "fromProcess"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8212: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/loadSso.ts -var loadSso_exports = {}; -__export(loadSso_exports, { - GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, - SSOClient: () => import_client_sso.SSOClient -}); -var import_client_sso; -var init_loadSso = __esm({ - "src/loadSso.ts"() { - "use strict"; - import_client_sso = __nccwpck_require__(43628); - } -}); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromSSO: () => fromSSO, - isSsoProfile: () => isSsoProfile, - validateSsoProfile: () => validateSsoProfile -}); -module.exports = __toCommonJS(index_exports); - -// src/fromSSO.ts - - - -// src/isSsoProfile.ts -var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); - -// src/resolveSSOCredentials.ts -var import_client = __nccwpck_require__(17582); -var import_token_providers = __nccwpck_require__(88967); -var import_property_provider = __nccwpck_require__(1104); -var import_shared_ini_file_loader = __nccwpck_require__(93438); -var SHOULD_FAIL_CREDENTIAL_CHAIN = false; -var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig, - parentClientConfig, - profile, - logger -}) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await (0, import_token_providers.fromSso)({ profile })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } else { - try { - token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); - const sso = ssoClient || new SSOClient2( - Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion - }) - ); - let ssoResp; - try { - ssoResp = await sso.send( - new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - }) - ); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { - roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} - } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); - } else { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); - } - return credentials; -}, "resolveSSOCredentials"); - -// src/validateSsoProfile.ts - -var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { - const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; - if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { - throw new import_property_provider.CredentialsProviderError( - `Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join( - ", " - )} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, - { tryNextLink: false, logger } - ); - } - return profile; -}, "validateSsoProfile"); - -// src/fromSSO.ts -var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const session = ssoSessions[profile.sso_session]; - const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; - if (ssoRegion && ssoRegion !== session.sso_region) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - profile.sso_region = session.sso_region; - profile.sso_start_url = session.sso_start_url; - } - const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile( - profile, - init.logger - ); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new import_property_provider.CredentialsProviderError( - 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', - { tryNextLink: false, logger: init.logger } - ); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } -}, "fromSSO"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 77753: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromTokenFile = void 0; -const client_1 = __nccwpck_require__(17582); -const property_provider_1 = __nccwpck_require__(1104); -const fs_1 = __nccwpck_require__(79896); -const fromWebToken_1 = __nccwpck_require__(92543); -const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; -const ENV_ROLE_ARN = "AWS_ROLE_ARN"; -const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; -const fromTokenFile = (init = {}) => async () => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); - } - return credentials; -}; -exports.fromTokenFile = fromTokenFile; - - -/***/ }), - -/***/ 92543: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(31058))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); - } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, - }); -}; -exports.fromWebToken = fromWebToken; - - -/***/ }), - -/***/ 47654: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(77753), module.exports); -__reExport(index_exports, __nccwpck_require__(92543), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 25164: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getHostHeaderPlugin: () => getHostHeaderPlugin, - hostHeaderMiddleware: () => hostHeaderMiddleware, - hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, - resolveHostHeaderConfig: () => resolveHostHeaderConfig -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(13494); -function resolveHostHeaderConfig(input) { - return input; -} -__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); -var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) return next(args); - const { request } = args; - const { handlerProtocol = "" } = options.requestHandler.metadata || {}; - if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { - delete request.headers["host"]; - request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); - } else if (!request.headers["host"]) { - let host = request.hostname; - if (request.port != null) host += `:${request.port}`; - request.headers["host"] = host; - } - return next(args); -}, "hostHeaderMiddleware"); -var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true -}; -var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, "applyToStack") -}), "getHostHeaderPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 65832: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getLoggerPlugin: () => getLoggerPlugin, - loggerMiddleware: () => loggerMiddleware, - loggerMiddlewareOptions: () => loggerMiddlewareOptions -}); -module.exports = __toCommonJS(index_exports); - -// src/loggerMiddleware.ts -var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - output: outputFilterSensitiveLog(outputWithoutMetadata), - metadata: $metadata - }); - return response; - } catch (error) { - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata - }); - throw error; - } -}, "loggerMiddleware"); -var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true -}; -var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, "applyToStack") -}), "getLoggerPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 39870: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getRecursionDetectionPlugin: () => getRecursionDetectionPlugin -}); -module.exports = __toCommonJS(index_exports); - -// src/configuration.ts -var recursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" -}; - -// src/getRecursionDetectionPlugin.ts -var import_recursionDetectionMiddleware = __nccwpck_require__(6971); -var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add((0, import_recursionDetectionMiddleware.recursionDetectionMiddleware)(), recursionDetectionMiddlewareOptions); - }, "applyToStack") -}), "getRecursionDetectionPlugin"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(6971), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6971: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.recursionDetectionMiddleware = void 0; -const lambda_invoke_store_1 = __nccwpck_require__(37453); -const protocol_http_1 = __nccwpck_require__(13494); -const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -const recursionDetectionMiddleware = () => (next) => async (args) => { - const { request } = args; - if (!protocol_http_1.HttpRequest.isInstance(request)) { - return next(args); - } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? - TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); - } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceIdFromEnv = process.env[ENV_TRACE_ID]; - const traceIdFromInvokeStore = lambda_invoke_store_1.InvokeStore.getXRayTraceId(); - const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; - const nonEmptyString = (str) => typeof str === "string" && str.length > 0; - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; - } - return next({ - ...args, - request, - }); -}; -exports.recursionDetectionMiddleware = recursionDetectionMiddleware; - - -/***/ }), - -/***/ 70997: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, - getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, - getUserAgentPlugin: () => getUserAgentPlugin, - resolveUserAgentConfig: () => resolveUserAgentConfig, - userAgentMiddleware: () => userAgentMiddleware -}); -module.exports = __toCommonJS(index_exports); - -// src/configurations.ts -var import_core = __nccwpck_require__(22744); -var DEFAULT_UA_APP_ID = void 0; -function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -__name(isValidUserAgentAppId, "isValidUserAgentAppId"); -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: /* @__PURE__ */ __name(async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - }, "userAgentAppId") - }); -} -__name(resolveUserAgentConfig, "resolveUserAgentConfig"); - -// src/user-agent-middleware.ts -var import_util_endpoints = __nccwpck_require__(16158); -var import_protocol_http = __nccwpck_require__(13494); - -// src/check-features.ts -var import_core2 = __nccwpck_require__(91446); -var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); - } - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); - } - } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - (0, import_core2.setFeature)(context, key, value); - } - } -} -__name(checkFeatures, "checkFeatures"); - -// src/constants.ts -var USER_AGENT = "user-agent"; -var X_AMZ_USER_AGENT = "x-amz-user-agent"; -var SPACE = " "; -var UA_NAME_SEPARATOR = "/"; -var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; -var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; -var UA_ESCAPE_CHAR = "-"; - -// src/encode-features.ts -var BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } else { - buffer += val; - } - continue; - } - break; - } - return buffer; -} -__name(encodeFeatures, "encodeFeatures"); - -// src/user-agent-middleware.ts -var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request)) { - return next(args); - } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push( - `m/${encodeFeatures( - Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) - )}` - ); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); - } - const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; - } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; - } - return next({ - ...args, - request - }); -}, "userAgentMiddleware"); -var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); - } - return [prefix, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index) => { - switch (index) { - case 0: - return item; - case 1: - return `${acc}/${item}`; - default: - return `${acc}#${item}`; - } - }, ""); -}, "escapeUserAgent"); -var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true -}; -var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, "applyToStack") -}), "getUserAgentPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8014: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(91446); -const util_middleware_1 = __nccwpck_require__(30954); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 42936: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(16158); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(67605); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 67605: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 54477: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sso-oidc/index.ts -var index_exports = {}; -__export(index_exports, { - $Command: () => import_smithy_client6.Command, - AccessDeniedException: () => AccessDeniedException, - AuthorizationPendingException: () => AuthorizationPendingException, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, - CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - InternalServerException: () => InternalServerException, - InvalidClientException: () => InvalidClientException, - InvalidGrantException: () => InvalidGrantException, - InvalidRequestException: () => InvalidRequestException, - InvalidScopeException: () => InvalidScopeException, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SlowDownException: () => SlowDownException, - UnauthorizedClientException: () => UnauthorizedClientException, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - __Client: () => import_smithy_client2.Client -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_middleware_host_header = __nccwpck_require__(25164); -var import_middleware_logger = __nccwpck_require__(65832); -var import_middleware_recursion_detection = __nccwpck_require__(39870); -var import_middleware_user_agent = __nccwpck_require__(70997); -var import_config_resolver = __nccwpck_require__(39316); -var import_core = __nccwpck_require__(22744); -var import_middleware_content_length = __nccwpck_require__(47212); -var import_middleware_endpoint = __nccwpck_require__(88205); -var import_middleware_retry = __nccwpck_require__(19618); -var import_smithy_client2 = __nccwpck_require__(61411); -var import_httpAuthSchemeProvider = __nccwpck_require__(8014); - -// src/submodules/sso-oidc/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_runtimeConfig = __nccwpck_require__(22791); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(26521); -var import_protocol_http = __nccwpck_require__(13494); -var import_smithy_client = __nccwpck_require__(61411); - -// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var SSOOIDCClient = class extends import_smithy_client2.Client { - static { - __name(this, "SSOOIDCClient"); - } - /** - * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/submodules/sso-oidc/SSOOIDC.ts -var import_smithy_client7 = __nccwpck_require__(61411); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(88205); -var import_middleware_serde = __nccwpck_require__(58305); -var import_smithy_client6 = __nccwpck_require__(61411); - -// src/submodules/sso-oidc/models/models_0.ts -var import_smithy_client4 = __nccwpck_require__(61411); - -// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts -var import_smithy_client3 = __nccwpck_require__(61411); -var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { - static { - __name(this, "SSOOIDCServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); - } -}; - -// src/submodules/sso-oidc/models/models_0.ts -var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { - static { - __name(this, "AccessDeniedException"); - } - name = "AccessDeniedException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be access_denied.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { - static { - __name(this, "AuthorizationPendingException"); - } - name = "AuthorizationPendingException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * authorization_pending.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenRequestFilterSensitiveLog"); -var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be expired_token.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - static { - __name(this, "InternalServerException"); - } - name = "InternalServerException"; - $fault = "server"; - /** - *

Single error code. For this exception the value will be server_error.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { - static { - __name(this, "InvalidClientException"); - } - name = "InvalidClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - static { - __name(this, "InvalidGrantException"); - } - name = "InvalidGrantException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_grant.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_request.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - static { - __name(this, "InvalidScopeException"); - } - name = "InvalidScopeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_scope.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { - static { - __name(this, "SlowDownException"); - } - name = "SlowDownException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be slow_down.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { - static { - __name(this, "UnauthorizedClientException"); - } - name = "UnauthorizedClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unauthorized_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { - static { - __name(this, "UnsupportedGrantTypeException"); - } - name = "UnsupportedGrantTypeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unsupported_grant_type.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; - -// src/submodules/sso-oidc/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(91446); -var import_core3 = __nccwpck_require__(22744); -var import_smithy_client5 = __nccwpck_require__(61411); -var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core3.requestBuilder)(input, context); - const headers = { - "content-type": "application/json" - }; - b.bp("/token"); - let body; - body = JSON.stringify( - (0, import_smithy_client5.take)(input, { - clientId: [], - clientSecret: [], - code: [], - codeVerifier: [], - deviceCode: [], - grantType: [], - redirectUri: [], - refreshToken: [], - scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") - }) - ); - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_CreateTokenCommand"); -var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client5.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client5.take)(data, { - accessToken: import_smithy_client5.expectString, - expiresIn: import_smithy_client5.expectInt32, - idToken: import_smithy_client5.expectString, - refreshToken: import_smithy_client5.expectString, - tokenType: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_CreateTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); - switch (errorCode) { - case "AccessDeniedException": - case "com.amazonaws.ssooidc#AccessDeniedException": - throw await de_AccessDeniedExceptionRes(parsedOutput, context); - case "AuthorizationPendingException": - case "com.amazonaws.ssooidc#AuthorizationPendingException": - throw await de_AuthorizationPendingExceptionRes(parsedOutput, context); - case "ExpiredTokenException": - case "com.amazonaws.ssooidc#ExpiredTokenException": - throw await de_ExpiredTokenExceptionRes(parsedOutput, context); - case "InternalServerException": - case "com.amazonaws.ssooidc#InternalServerException": - throw await de_InternalServerExceptionRes(parsedOutput, context); - case "InvalidClientException": - case "com.amazonaws.ssooidc#InvalidClientException": - throw await de_InvalidClientExceptionRes(parsedOutput, context); - case "InvalidGrantException": - case "com.amazonaws.ssooidc#InvalidGrantException": - throw await de_InvalidGrantExceptionRes(parsedOutput, context); - case "InvalidRequestException": - case "com.amazonaws.ssooidc#InvalidRequestException": - throw await de_InvalidRequestExceptionRes(parsedOutput, context); - case "InvalidScopeException": - case "com.amazonaws.ssooidc#InvalidScopeException": - throw await de_InvalidScopeExceptionRes(parsedOutput, context); - case "SlowDownException": - case "com.amazonaws.ssooidc#SlowDownException": - throw await de_SlowDownExceptionRes(parsedOutput, context); - case "UnauthorizedClientException": - case "com.amazonaws.ssooidc#UnauthorizedClientException": - throw await de_UnauthorizedClientExceptionRes(parsedOutput, context); - case "UnsupportedGrantTypeException": - case "com.amazonaws.ssooidc#UnsupportedGrantTypeException": - throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody, - errorCode - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AccessDeniedExceptionRes"); -var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AuthorizationPendingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AuthorizationPendingExceptionRes"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_ExpiredTokenExceptionRes"); -var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InternalServerExceptionRes"); -var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidClientExceptionRes"); -var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidGrantException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidGrantExceptionRes"); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidScopeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidScopeExceptionRes"); -var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new SlowDownException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_SlowDownExceptionRes"); -var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedClientExceptionRes"); -var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnsupportedGrantTypeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnsupportedGrantTypeExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { - static { - __name(this, "CreateTokenCommand"); - } -}; - -// src/submodules/sso-oidc/SSOOIDC.ts -var commands = { - CreateTokenCommand -}; -var SSOOIDC = class extends SSOOIDCClient { - static { - __name(this, "SSOOIDC"); - } -}; -(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 22791: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(77507)); -const core_1 = __nccwpck_require__(91446); -const util_user_agent_node_1 = __nccwpck_require__(9082); -const config_resolver_1 = __nccwpck_require__(39316); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(61814); -const node_http_handler_1 = __nccwpck_require__(95493); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(13892); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 13892: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(91446); -const core_2 = __nccwpck_require__(22744); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(85792); -const util_base64_1 = __nccwpck_require__(82763); -const util_utf8_1 = __nccwpck_require__(85339); -const httpAuthSchemeProvider_1 = __nccwpck_require__(8014); -const endpointResolver_1 = __nccwpck_require__(42936); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 56001: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.STSClient = exports.__Client = void 0; -const middleware_host_header_1 = __nccwpck_require__(25164); -const middleware_logger_1 = __nccwpck_require__(65832); -const middleware_recursion_detection_1 = __nccwpck_require__(39870); -const middleware_user_agent_1 = __nccwpck_require__(70997); -const config_resolver_1 = __nccwpck_require__(39316); -const core_1 = __nccwpck_require__(22744); -const middleware_content_length_1 = __nccwpck_require__(47212); -const middleware_endpoint_1 = __nccwpck_require__(88205); -const middleware_retry_1 = __nccwpck_require__(19618); -const smithy_client_1 = __nccwpck_require__(61411); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(5037); -const EndpointParameters_1 = __nccwpck_require__(64361); -const runtimeConfig_1 = __nccwpck_require__(18452); -const runtimeExtensions_1 = __nccwpck_require__(83488); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; - - -/***/ }), - -/***/ 54710: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; - - -/***/ }), - -/***/ 5037: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(91446); -const util_middleware_1 = __nccwpck_require__(30954); -const STSClient_1 = __nccwpck_require__(56001); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 64361: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - - -/***/ }), - -/***/ 35075: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(16158); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(79144); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 79144: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; -const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "String" }, n = { [F]: true, "default": false, [G]: "Boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; -const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 31058: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sts/index.ts -var index_exports = {}; -__export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(56001), module.exports); - -// src/submodules/sts/STS.ts -var import_smithy_client6 = __nccwpck_require__(61411); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(88205); -var import_middleware_serde = __nccwpck_require__(58305); -var import_smithy_client4 = __nccwpck_require__(61411); -var import_EndpointParameters = __nccwpck_require__(64361); - -// src/submodules/sts/models/models_0.ts -var import_smithy_client2 = __nccwpck_require__(61411); - -// src/submodules/sts/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(61411); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "STSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; - -// src/submodules/sts/models/models_0.ts -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); - } - name = "MalformedPolicyDocumentException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); - } - name = "PackedPolicyTooLargeException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); - } - name = "RegionDisabledException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } -}; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); - } - name = "IDPRejectedClaimException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } -}; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); - } - name = "InvalidIdentityTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } -}; -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); - } - name = "IDPCommunicationErrorException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } -}; - -// src/submodules/sts/protocols/Aws_query.ts -var import_core = __nccwpck_require__(91446); -var import_protocol_http = __nccwpck_require__(13494); -var import_smithy_client3 = __nccwpck_require__(61411); -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(output.body, context) - }; - const errorCode = loadQueryErrorCode(output, parsedOutput.body); - switch (errorCode) { - case "ExpiredTokenException": - case "com.amazonaws.sts#ExpiredTokenException": - throw await de_ExpiredTokenExceptionRes(parsedOutput, context); - case "MalformedPolicyDocument": - case "com.amazonaws.sts#MalformedPolicyDocumentException": - throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); - case "PackedPolicyTooLarge": - case "com.amazonaws.sts#PackedPolicyTooLargeException": - throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); - case "RegionDisabledException": - case "com.amazonaws.sts#RegionDisabledException": - throw await de_RegionDisabledExceptionRes(parsedOutput, context); - case "IDPCommunicationError": - case "com.amazonaws.sts#IDPCommunicationErrorException": - throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); - case "IDPRejectedClaim": - case "com.amazonaws.sts#IDPRejectedClaimException": - throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context); - case "InvalidIdentityToken": - case "com.amazonaws.sts#InvalidIdentityTokenException": - throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody: parsedBody.Error, - errorCode - }); - } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); - } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; - } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - const memberEntries = se_PolicyDescriptorType(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; - } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; - } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - const memberEntries = se_ProvidedContext(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; - } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; - } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - const memberEntries = se_Tag(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); - } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); - } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); - } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); - } - return contents; -}, "de_Credentials"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_ExpiredTokenException"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers - }; - if (resolvedHostname !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" -}; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _K = "Key"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _SAK = "SecretAccessKey"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TTK = "TransitiveTagKeys"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadQueryErrorCode"); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); - } -}; - -// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(88205); -var import_middleware_serde2 = __nccwpck_require__(58305); -var import_smithy_client5 = __nccwpck_require__(61411); -var import_EndpointParameters2 = __nccwpck_require__(64361); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { - static { - __name(this, "AssumeRoleWithWebIdentityCommand"); - } -}; - -// src/submodules/sts/STS.ts -var import_STSClient = __nccwpck_require__(56001); -var commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand -}; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); - } -}; -(0, import_smithy_client6.createAggregatedClient)(commands, STS); - -// src/submodules/sts/index.ts -var import_EndpointParameters3 = __nccwpck_require__(64361); - -// src/submodules/sts/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(17582); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/submodules/sts/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(56001); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 18452: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(77507)); -const core_1 = __nccwpck_require__(91446); -const util_user_agent_node_1 = __nccwpck_require__(9082); -const config_resolver_1 = __nccwpck_require__(39316); -const core_2 = __nccwpck_require__(22744); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(61814); -const node_http_handler_1 = __nccwpck_require__(95493); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(57349); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 57349: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(91446); -const core_2 = __nccwpck_require__(22744); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(85792); -const util_base64_1 = __nccwpck_require__(82763); -const util_utf8_1 = __nccwpck_require__(85339); -const httpAuthSchemeProvider_1 = __nccwpck_require__(5037); -const endpointResolver_1 = __nccwpck_require__(35075); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2011-06-15", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "STS", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 83488: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveRuntimeExtensions = void 0; -const region_config_resolver_1 = __nccwpck_require__(26521); -const protocol_http_1 = __nccwpck_require__(13494); -const smithy_client_1 = __nccwpck_require__(61411); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(54710); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; - - -/***/ }), - -/***/ 26521: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, - resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, - resolveRegionConfig: () => resolveRegionConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/index.ts -var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - } - }; -}, "getAwsRegionExtensionConfiguration"); -var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; -}, "resolveAwsRegionExtensionConfiguration"); - -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" -}; - -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); - -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); - -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 88967: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromEnvSigningName: () => fromEnvSigningName, - fromSso: () => fromSso, - fromStatic: () => fromStatic, - nodeProvider: () => nodeProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/fromEnvSigningName.ts -var import_client = __nccwpck_require__(17582); -var import_httpAuthSchemes = __nccwpck_require__(7321); -var import_property_provider = __nccwpck_require__(1104); -var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); - if (!(bearerTokenKey in process.env)) { - throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - const token = { token: process.env[bearerTokenKey] }; - (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; -}, "fromEnvSigningName"); - -// src/fromSso.ts - - - -// src/constants.ts -var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; -var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - -// src/getSsoOidcClient.ts -var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(54477))); - const ssoOidcClient = new SSOOIDCClient( - Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger - }) - ); - return ssoOidcClient; -}, "getSsoOidcClient"); - -// src/getNewSsoOidcToken.ts -var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(54477))); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send( - new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - }) - ); -}, "getNewSsoOidcToken"); - -// src/validateTokenExpiry.ts - -var validateTokenExpiry = /* @__PURE__ */ __name((token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } -}, "validateTokenExpiry"); - -// src/validateTokenKey.ts - -var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new import_property_provider.TokenProviderError( - `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, - false - ); - } -}, "validateTokenKey"); - -// src/writeSSOTokenToFile.ts -var import_shared_ini_file_loader = __nccwpck_require__(93438); -var import_fs = __nccwpck_require__(79896); -var { writeFile } = import_fs.promises; -var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { - const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}, "writeSSOTokenToFile"); - -// src/fromSso.ts -var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); -var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); - } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' could not be found in shared credentials file.`, - false - ); - } - for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { - if (!ssoSession[ssoSessionRequiredKey]) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, - false - ); - } - } - const ssoStartUrl = ssoSession["sso_start_url"]; - const ssoRegion = ssoSession["sso_region"]; - let ssoToken; - try { - ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); - } catch (e) { - throw new import_property_provider.TokenProviderError( - `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, - false - ); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; - } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken - }); - } catch (error) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration - }; - } catch (error) { - validateTokenExpiry(existingToken); - return existingToken; - } -}, "fromSso"); - -// src/fromStatic.ts - -var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); - } - return token; -}, "fromStatic"); - -// src/nodeProvider.ts - -var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)(fromSso(init), async () => { - throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); - }), - (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, - (token) => token.expiration !== void 0 -), "nodeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 16158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ConditionObject: () => import_util_endpoints.ConditionObject, - DeprecatedObject: () => import_util_endpoints.DeprecatedObject, - EndpointError: () => import_util_endpoints.EndpointError, - EndpointObject: () => import_util_endpoints.EndpointObject, - EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, - EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, - EndpointParams: () => import_util_endpoints.EndpointParams, - EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, - EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, - ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, - EvaluateOptions: () => import_util_endpoints.EvaluateOptions, - Expression: () => import_util_endpoints.Expression, - FunctionArgv: () => import_util_endpoints.FunctionArgv, - FunctionObject: () => import_util_endpoints.FunctionObject, - FunctionReturn: () => import_util_endpoints.FunctionReturn, - ParameterObject: () => import_util_endpoints.ParameterObject, - ReferenceObject: () => import_util_endpoints.ReferenceObject, - ReferenceRecord: () => import_util_endpoints.ReferenceRecord, - RuleSetObject: () => import_util_endpoints.RuleSetObject, - RuleSetRules: () => import_util_endpoints.RuleSetRules, - TreeRuleObject: () => import_util_endpoints.TreeRuleObject, - awsEndpointFunctions: () => awsEndpointFunctions, - getUserAgentPrefix: () => getUserAgentPrefix, - isIpAddress: () => import_util_endpoints.isIpAddress, - partition: () => partition, - resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, - resolveEndpoint: () => import_util_endpoints.resolveEndpoint, - setPartitionInfo: () => setPartitionInfo, - toEndpointV1: () => toEndpointV1, - useDefaultPartitionInfo: () => useDefaultPartitionInfo -}); -module.exports = __toCommonJS(index_exports); - -// src/aws.ts - - -// src/lib/aws/isVirtualHostableS3Bucket.ts - - -// src/lib/isIpAddress.ts -var import_util_endpoints = __nccwpck_require__(79674); - -// src/lib/aws/isVirtualHostableS3Bucket.ts -var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!(0, import_util_endpoints.isValidHostLabel)(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if ((0, import_util_endpoints.isIpAddress)(value)) { - return false; - } - return true; -}, "isVirtualHostableS3Bucket"); - -// src/lib/aws/parseArn.ts -var ARN_DELIMITER = ":"; -var RESOURCE_DELIMITER = "/"; -var parseArn = /* @__PURE__ */ __name((value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; -}, "parseArn"); - -// src/lib/aws/partitions.json -var partitions_default = { - partitions: [{ - id: "aws", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-east-1", - name: "aws", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "ap-northeast-1": { - description: "Asia Pacific (Tokyo)" - }, - "ap-northeast-2": { - description: "Asia Pacific (Seoul)" - }, - "ap-northeast-3": { - description: "Asia Pacific (Osaka)" - }, - "ap-south-1": { - description: "Asia Pacific (Mumbai)" - }, - "ap-south-2": { - description: "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1": { - description: "Asia Pacific (Singapore)" - }, - "ap-southeast-2": { - description: "Asia Pacific (Sydney)" - }, - "ap-southeast-3": { - description: "Asia Pacific (Jakarta)" - }, - "ap-southeast-4": { - description: "Asia Pacific (Melbourne)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-6": { - description: "Asia Pacific (New Zealand)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "aws global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "eu-central-1": { - description: "Europe (Frankfurt)" - }, - "eu-central-2": { - description: "Europe (Zurich)" - }, - "eu-north-1": { - description: "Europe (Stockholm)" - }, - "eu-south-1": { - description: "Europe (Milan)" - }, - "eu-south-2": { - description: "Europe (Spain)" - }, - "eu-west-1": { - description: "Europe (Ireland)" - }, - "eu-west-2": { - description: "Europe (London)" - }, - "eu-west-3": { - description: "Europe (Paris)" - }, - "il-central-1": { - description: "Israel (Tel Aviv)" - }, - "me-central-1": { - description: "Middle East (UAE)" - }, - "me-south-1": { - description: "Middle East (Bahrain)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "sa-east-1": { - description: "South America (Sao Paulo)" - }, - "us-east-1": { - description: "US East (N. Virginia)" - }, - "us-east-2": { - description: "US East (Ohio)" - }, - "us-west-1": { - description: "US West (N. California)" - }, - "us-west-2": { - description: "US West (Oregon)" - } - } - }, { - id: "aws-cn", - outputs: { - dnsSuffix: "amazonaws.com.cn", - dualStackDnsSuffix: "api.amazonwebservices.com.cn", - implicitGlobalRegion: "cn-northwest-1", - name: "aws-cn", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^cn\\-\\w+\\-\\d+$", - regions: { - "aws-cn-global": { - description: "aws-cn global region" - }, - "cn-north-1": { - description: "China (Beijing)" - }, - "cn-northwest-1": { - description: "China (Ningxia)" - } - } - }, { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "api.amazonwebservices.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" - } - } - }, { - id: "aws-iso", - outputs: { - dnsSuffix: "c2s.ic.gov", - dualStackDnsSuffix: "api.aws.ic.gov", - implicitGlobalRegion: "us-iso-east-1", - name: "aws-iso", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - regions: { - "aws-iso-global": { - description: "aws-iso global region" - }, - "us-iso-east-1": { - description: "US ISO East" - }, - "us-iso-west-1": { - description: "US ISO WEST" - } - } - }, { - id: "aws-iso-b", - outputs: { - dnsSuffix: "sc2s.sgov.gov", - dualStackDnsSuffix: "api.aws.scloud", - implicitGlobalRegion: "us-isob-east-1", - name: "aws-iso-b", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - regions: { - "aws-iso-b-global": { - description: "aws-iso-b global region" - }, - "us-isob-east-1": { - description: "US ISOB East (Ohio)" - } - } - }, { - id: "aws-iso-e", - outputs: { - dnsSuffix: "cloud.adc-e.uk", - dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", - implicitGlobalRegion: "eu-isoe-west-1", - name: "aws-iso-e", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", - regions: { - "aws-iso-e-global": { - description: "aws-iso-e global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, { - id: "aws-iso-f", - outputs: { - dnsSuffix: "csp.hci.ic.gov", - dualStackDnsSuffix: "api.aws.hci.ic.gov", - implicitGlobalRegion: "us-isof-south-1", - name: "aws-iso-f", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", - regions: { - "aws-iso-f-global": { - description: "aws-iso-f global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, { - id: "aws-us-gov", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-gov-west-1", - name: "aws-us-gov", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - regions: { - "aws-us-gov-global": { - description: "aws-us-gov global region" - }, - "us-gov-east-1": { - description: "AWS GovCloud (US-East)" - }, - "us-gov-west-1": { - description: "AWS GovCloud (US-West)" - } - } - }], - version: "1.1" -}; - -// src/lib/aws/partition.ts -var selectedPartitionsInfo = partitions_default; -var selectedUserAgentPrefix = ""; -var partition = /* @__PURE__ */ __name((value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } - } - } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; - } - } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); - if (!DEFAULT_PARTITION) { - throw new Error( - "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist." - ); - } - return { - ...DEFAULT_PARTITION.outputs - }; -}, "partition"); -var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}, "setPartitionInfo"); -var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { - setPartitionInfo(partitions_default, ""); -}, "useDefaultPartitionInfo"); -var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); - -// src/aws.ts -var awsEndpointFunctions = { - isVirtualHostableS3Bucket, - parseArn, - partition -}; -import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; - -// src/resolveDefaultAwsRegionalEndpointsConfig.ts -var import_url_parser = __nccwpck_require__(85792); -var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); - } - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - return toEndpointV1( - input.endpointProvider( - { - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: void 0 - }, - { logger: input.logger } - ) - ); - }; - } - return input; -}, "resolveDefaultAwsRegionalEndpointsConfig"); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); - -// src/resolveEndpoint.ts - - -// src/types/EndpointError.ts - - -// src/types/EndpointRuleObject.ts - - -// src/types/ErrorRuleObject.ts - - -// src/types/RuleSetObject.ts - - -// src/types/TreeRuleObject.ts - - -// src/types/shared.ts - -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, - UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, - UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, - createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, - crtAvailability: () => crtAvailability, - defaultUserAgent: () => defaultUserAgent -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultUserAgent.ts -var import_os = __nccwpck_require__(70857); -var import_process = __nccwpck_require__(932); - -// src/crt-availability.ts -var crtAvailability = { - isCrtAvailable: false -}; - -// src/is-crt-available.ts -var isCrtAvailable = /* @__PURE__ */ __name(() => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}, "isCrtAvailable"); - -// src/defaultUserAgent.ts -var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - // sdk-metadata - ["aws-sdk-js", clientVersion], - // ua-metadata - ["ua", "2.1"], - // os-metadata - [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], - // language-metadata - // ECMAScript edition doesn't matter in JS, so no version needed. - ["lang/js"], - ["md/nodejs", `${import_process.versions.node}`] - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (import_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}, "createDefaultUserAgentProvider"); -var defaultUserAgent = createDefaultUserAgentProvider; - -// src/nodeAppIdConfigOptions.ts -var import_middleware_user_agent = __nccwpck_require__(70997); -var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -var NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), - default: import_middleware_user_agent.DEFAULT_UA_APP_ID -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 2344: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); - -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); - -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } - static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); - } -}; - -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } - static { - __name(this, "XmlNode"); - } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; - } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 22744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(50892); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(30954); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; - } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } - } - } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } - } - return preferredAuthOptions; -}, "resolveAuthOptions"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); - } - return map; -} -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" -}; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(58305); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemePlugin"); - -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(13494); - -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); - -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" -}; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); - }, "applyToStack") -}), "getHttpSigningPlugin"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); - -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; - } - cursor = cursor[step]; - } - return cursor; -}, "get"); - -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(86752); - -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; - } - context.__smithy_context.features[feature] = value; -} -__name(setFeature, "setFeature"); - -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } - } - } - static { - __name(this, "DefaultIdentityProviderConfig"); - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { - static { - __name(this, "HttpApiKeyAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); - } - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts - -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; - } -}; - -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; - } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; - } - return resolved; - }; -}, "memoizeIdentityProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 91467: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/cbor/index.ts -var index_exports = {}; -__export(index_exports, { - CborCodec: () => CborCodec, - CborShapeDeserializer: () => CborShapeDeserializer, - CborShapeSerializer: () => CborShapeSerializer, - SmithyRpcV2CborProtocol: () => SmithyRpcV2CborProtocol, - buildHttpRpcRequest: () => buildHttpRpcRequest, - cbor: () => cbor, - checkCborResponse: () => checkCborResponse, - dateToTag: () => dateToTag, - loadSmithyRpcV2CborErrorCode: () => loadSmithyRpcV2CborErrorCode, - parseCborBody: () => parseCborBody, - parseCborErrorBody: () => parseCborErrorBody, - tag: () => tag, - tagSymbol: () => tagSymbol -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/cbor/cbor-decode.ts -var import_serde = __nccwpck_require__(98520); -var import_util_utf8 = __nccwpck_require__(85339); - -// src/submodules/cbor/cbor-types.ts -var majorUint64 = 0; -var majorNegativeInt64 = 1; -var majorUnstructuredByteString = 2; -var majorUtf8String = 3; -var majorList = 4; -var majorMap = 5; -var majorTag = 6; -var majorSpecial = 7; -var specialFalse = 20; -var specialTrue = 21; -var specialNull = 22; -var specialUndefined = 23; -var extendedOneByte = 24; -var extendedFloat16 = 25; -var extendedFloat32 = 26; -var extendedFloat64 = 27; -var minorIndefinite = 31; -function alloc(size) { - return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); -} -var tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); -function tag(data2) { - data2[tagSymbol] = true; - return data2; -} - -// src/submodules/cbor/cbor-decode.ts -var USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; -var USE_BUFFER = typeof Buffer !== "undefined"; -var payload = alloc(0); -var dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -var textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; -var _offset = 0; -function setPayload(bytes) { - payload = bytes; - dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -} -function decode(at, to) { - if (at >= to) { - throw new Error("unexpected end of (decode) payload."); - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - switch (major) { - case majorUint64: - case majorNegativeInt64: - case majorTag: - let unsignedInt; - let offset; - if (minor < 24) { - unsignedInt = minor; - offset = 1; - } else { - switch (minor) { - case extendedOneByte: - case extendedFloat16: - case extendedFloat32: - case extendedFloat64: - const countLength = minorValueToArgumentLength[minor]; - const countOffset = countLength + 1; - offset = countOffset; - if (to - at < countOffset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - unsignedInt = payload[countIndex]; - } else if (countLength === 2) { - unsignedInt = dataView.getUint16(countIndex); - } else if (countLength === 4) { - unsignedInt = dataView.getUint32(countIndex); - } else { - unsignedInt = dataView.getBigUint64(countIndex); - } - break; - default: - throw new Error(`unexpected minor value ${minor}.`); - } - } - if (major === majorUint64) { - _offset = offset; - return castBigInt(unsignedInt); - } else if (major === majorNegativeInt64) { - let negativeInt; - if (typeof unsignedInt === "bigint") { - negativeInt = BigInt(-1) - unsignedInt; - } else { - negativeInt = -1 - unsignedInt; - } - _offset = offset; - return castBigInt(negativeInt); - } else { - if (minor === 2 || minor === 3) { - const length = decodeCount(at + offset, to); - let b = BigInt(0); - const start = at + offset + _offset; - for (let i = start; i < start + length; ++i) { - b = b << BigInt(8) | BigInt(payload[i]); - } - _offset = offset + _offset + length; - return minor === 3 ? -b - BigInt(1) : b; - } else if (minor === 4) { - const decimalFraction = decode(at + offset, to); - const [exponent, mantissa] = decimalFraction; - const normalizer = mantissa < 0 ? -1 : 1; - const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); - let numericString; - const sign = mantissa < 0 ? "-" : ""; - numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); - numericString = numericString.replace(/^0+/g, ""); - if (numericString === "") { - numericString = "0"; - } - if (numericString[0] === ".") { - numericString = "0" + numericString; - } - numericString = sign + numericString; - _offset = offset + _offset; - return (0, import_serde.nv)(numericString); - } else { - const value = decode(at + offset, to); - const valueOffset = _offset; - _offset = offset + valueOffset; - return tag({ tag: castBigInt(unsignedInt), value }); - } - } - case majorUtf8String: - case majorMap: - case majorList: - case majorUnstructuredByteString: - if (minor === minorIndefinite) { - switch (major) { - case majorUtf8String: - return decodeUtf8StringIndefinite(at, to); - case majorMap: - return decodeMapIndefinite(at, to); - case majorList: - return decodeListIndefinite(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteStringIndefinite(at, to); - } - } else { - switch (major) { - case majorUtf8String: - return decodeUtf8String(at, to); - case majorMap: - return decodeMap(at, to); - case majorList: - return decodeList(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteString(at, to); - } - } - default: - return decodeSpecial(at, to); - } -} -function bytesToUtf8(bytes, at, to) { - if (USE_BUFFER && bytes.constructor?.name === "Buffer") { - return bytes.toString("utf-8", at, to); - } - if (textDecoder) { - return textDecoder.decode(bytes.subarray(at, to)); - } - return (0, import_util_utf8.toUtf8)(bytes.subarray(at, to)); -} -function demote(bigInteger) { - const num = Number(bigInteger); - if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { - console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); - } - return num; -} -var minorValueToArgumentLength = { - [extendedOneByte]: 1, - [extendedFloat16]: 2, - [extendedFloat32]: 4, - [extendedFloat64]: 8 -}; -function bytesToFloat16(a, b) { - const sign = a >> 7; - const exponent = (a & 124) >> 2; - const fraction = (a & 3) << 8 | b; - const scalar = sign === 0 ? 1 : -1; - let exponentComponent; - let summation; - if (exponent === 0) { - if (fraction === 0) { - return 0; - } else { - exponentComponent = Math.pow(2, 1 - 15); - summation = 0; - } - } else if (exponent === 31) { - if (fraction === 0) { - return scalar * Infinity; - } else { - return NaN; - } - } else { - exponentComponent = Math.pow(2, exponent - 15); - summation = 1; - } - summation += fraction / 1024; - return scalar * (exponentComponent * summation); -} -function decodeCount(at, to) { - const minor = payload[at] & 31; - if (minor < 24) { - _offset = 1; - return minor; - } - if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) { - const countLength = minorValueToArgumentLength[minor]; - _offset = countLength + 1; - if (to - at < _offset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - return payload[countIndex]; - } else if (countLength === 2) { - return dataView.getUint16(countIndex); - } else if (countLength === 4) { - return dataView.getUint32(countIndex); - } - return demote(dataView.getBigUint64(countIndex)); - } - throw new Error(`unexpected minor value ${minor}.`); -} -function decodeUtf8String(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`string len ${length} greater than remaining buf len.`); - } - const value = bytesToUtf8(payload, at, at + length); - _offset = offset + length; - return value; -} -function decodeUtf8StringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector.length); - data2.set(vector, 0); - _offset = at - base + 2; - return bytesToUtf8(data2, 0, data2.length); - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); - } - } - throw new Error("expected break marker."); -} -function decodeUnstructuredByteString(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); - } - const value = payload.subarray(at, at + length); - _offset = offset + length; - return value; -} -function decodeUnstructuredByteStringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector.length); - data2.set(vector, 0); - _offset = at - base + 2; - return data2; - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUnstructuredByteString) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); - } - } - throw new Error("expected break marker."); -} -function decodeList(at, to) { - const listDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const list = Array(listDataLength); - for (let i = 0; i < listDataLength; ++i) { - const item = decode(at, to); - const itemOffset = _offset; - list[i] = item; - at += itemOffset; - } - _offset = offset + (at - base); - return list; -} -function decodeListIndefinite(at, to) { - at += 1; - const list = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - _offset = at - base + 2; - return list; - } - const item = decode(at, to); - const n = _offset; - at += n; - list.push(item); - } - throw new Error("expected break marker."); -} -function decodeMap(at, to) { - const mapDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const map = {}; - for (let i = 0; i < mapDataLength; ++i) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key at index ${at}.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; - } - _offset = offset + (at - base); - return map; -} -function decodeMapIndefinite(at, to) { - at += 1; - const base = at; - const map = {}; - for (; at < to; ) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - if (payload[at] === 255) { - _offset = at - base + 2; - return map; - } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; - } - throw new Error("expected break marker."); -} -function decodeSpecial(at, to) { - const minor = payload[at] & 31; - switch (minor) { - case specialTrue: - case specialFalse: - _offset = 1; - return minor === specialTrue; - case specialNull: - _offset = 1; - return null; - case specialUndefined: - _offset = 1; - return null; - case extendedFloat16: - if (to - at < 3) { - throw new Error("incomplete float16 at end of buf."); - } - _offset = 3; - return bytesToFloat16(payload[at + 1], payload[at + 2]); - case extendedFloat32: - if (to - at < 5) { - throw new Error("incomplete float32 at end of buf."); - } - _offset = 5; - return dataView.getFloat32(at + 1); - case extendedFloat64: - if (to - at < 9) { - throw new Error("incomplete float64 at end of buf."); - } - _offset = 9; - return dataView.getFloat64(at + 1); - default: - throw new Error(`unexpected minor value ${minor}.`); - } -} -function castBigInt(bigInt) { - if (typeof bigInt === "number") { - return bigInt; - } - const num = Number(bigInt); - if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { - return num; - } - return bigInt; -} - -// src/submodules/cbor/cbor-encode.ts -var import_serde2 = __nccwpck_require__(98520); -var import_util_utf82 = __nccwpck_require__(85339); -var USE_BUFFER2 = typeof Buffer !== "undefined"; -var initialSize = 2048; -var data = alloc(initialSize); -var dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); -var cursor = 0; -function ensureSpace(bytes) { - const remaining = data.byteLength - cursor; - if (remaining < bytes) { - if (cursor < 16e6) { - resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); - } else { - resize(data.byteLength + bytes + 16e6); - } - } -} -function toUint8Array() { - const out = alloc(cursor); - out.set(data.subarray(0, cursor), 0); - cursor = 0; - return out; -} -function resize(size) { - const old = data; - data = alloc(size); - if (old) { - if (old.copy) { - old.copy(data, 0, 0, old.byteLength); - } else { - data.set(old, 0); - } - } - dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); -} -function encodeHeader(major, value) { - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 1 << 8) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 1 << 16) { - data[cursor++] = major << 5 | extendedFloat16; - dataView2.setUint16(cursor, value); - cursor += 2; - } else if (value < 2 ** 32) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; - } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); - cursor += 8; - } -} -function encode(_input) { - const encodeStack = [_input]; - while (encodeStack.length) { - const input = encodeStack.pop(); - ensureSpace(typeof input === "string" ? input.length * 4 : 64); - if (typeof input === "string") { - if (USE_BUFFER2) { - encodeHeader(majorUtf8String, Buffer.byteLength(input)); - cursor += data.write(input, cursor); - } else { - const bytes = (0, import_util_utf82.fromUtf8)(input); - encodeHeader(majorUtf8String, bytes.byteLength); - data.set(bytes, cursor); - cursor += bytes.byteLength; - } - continue; - } else if (typeof input === "number") { - if (Number.isInteger(input)) { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - 1; - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = value >> 8; - data[cursor++] = value; - } else if (value < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; - } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, BigInt(value)); - cursor += 8; - } - continue; - } - data[cursor++] = majorSpecial << 5 | extendedFloat64; - dataView2.setFloat64(cursor, input); - cursor += 8; - continue; - } else if (typeof input === "bigint") { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - BigInt(1); - const n = Number(value); - if (n < 24) { - data[cursor++] = major << 5 | n; - } else if (n < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = n; - } else if (n < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = n >> 8; - data[cursor++] = n & 255; - } else if (n < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, n); - cursor += 4; - } else if (value < BigInt("18446744073709551616")) { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, value); - cursor += 8; - } else { - const binaryBigInt = value.toString(2); - const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); - let b = value; - let i = 0; - while (bigIntBytes.byteLength - ++i >= 0) { - bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); - b >>= BigInt(8); - } - ensureSpace(bigIntBytes.byteLength * 2); - data[cursor++] = nonNegative ? 194 : 195; - if (USE_BUFFER2) { - encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); - } else { - encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); - } - data.set(bigIntBytes, cursor); - cursor += bigIntBytes.byteLength; - } - continue; - } else if (input === null) { - data[cursor++] = majorSpecial << 5 | specialNull; - continue; - } else if (typeof input === "boolean") { - data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse); - continue; - } else if (typeof input === "undefined") { - throw new Error("@smithy/core/cbor: client may not serialize undefined value."); - } else if (Array.isArray(input)) { - for (let i = input.length - 1; i >= 0; --i) { - encodeStack.push(input[i]); - } - encodeHeader(majorList, input.length); - continue; - } else if (typeof input.byteLength === "number") { - ensureSpace(input.length * 2); - encodeHeader(majorUnstructuredByteString, input.length); - data.set(input, cursor); - cursor += input.byteLength; - continue; - } else if (typeof input === "object") { - if (input instanceof import_serde2.NumericValue) { - const decimalIndex = input.string.indexOf("."); - const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; - const mantissa = BigInt(input.string.replace(".", "")); - data[cursor++] = 196; - encodeStack.push(mantissa); - encodeStack.push(exponent); - encodeHeader(majorList, 2); - continue; - } - if (input[tagSymbol]) { - if ("tag" in input && "value" in input) { - encodeStack.push(input.value); - encodeHeader(majorTag, input.tag); - continue; - } else { - throw new Error( - "tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input) - ); - } - } - const keys = Object.keys(input); - for (let i = keys.length - 1; i >= 0; --i) { - const key = keys[i]; - encodeStack.push(input[key]); - encodeStack.push(key); - } - encodeHeader(majorMap, keys.length); - continue; - } - throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); - } -} - -// src/submodules/cbor/cbor.ts -var cbor = { - deserialize(payload2) { - setPayload(payload2); - return decode(0, payload2.length); - }, - serialize(input) { - try { - encode(input); - return toUint8Array(); - } catch (e) { - toUint8Array(); - throw e; - } - }, - /** - * @public - * @param size - byte length to allocate. - * - * This may be used to garbage collect the CBOR - * shared encoding buffer space, - * e.g. resizeEncodingBuffer(0); - * - * This may also be used to pre-allocate more space for - * CBOR encoding, e.g. resizeEncodingBuffer(100_000_000); - */ - resizeEncodingBuffer(size) { - resize(size); - } -}; - -// src/submodules/cbor/parseCborBody.ts -var import_protocols = __nccwpck_require__(86752); -var import_protocol_http = __nccwpck_require__(13494); -var import_util_body_length_browser = __nccwpck_require__(84916); -var parseCborBody = (streamBody, context) => { - return (0, import_protocols.collectBody)(streamBody, context).then(async (bytes) => { - if (bytes.length) { - try { - return cbor.deserialize(bytes); - } catch (e) { - Object.defineProperty(e, "$responseBodyText", { - value: context.utf8Encoder(bytes) - }); - throw e; - } - } - return {}; - }); -}; -var dateToTag = (date) => { - return tag({ - tag: 1, - value: date.getTime() / 1e3 - }); -}; -var parseCborErrorBody = async (errorBody, context) => { - const value = await parseCborBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}; -var loadSmithyRpcV2CborErrorCode = (output, data2) => { - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - if (data2["__type"] !== void 0) { - return sanitizeErrorCode(data2["__type"]); - } - const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code"); - if (codeKey && data2[codeKey] !== void 0) { - return sanitizeErrorCode(data2[codeKey]); - } -}; -var checkCborResponse = (response) => { - if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { - throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); - } -}; -var buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers: { - // intentional copy. - ...headers - } - }; - if (resolvedHostname !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - try { - contents.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(body)); - } catch (e) { - } - } - return new import_protocol_http.HttpRequest(contents); -}; - -// src/submodules/cbor/SmithyRpcV2CborProtocol.ts -var import_protocols2 = __nccwpck_require__(86752); -var import_schema2 = __nccwpck_require__(41320); -var import_util_middleware = __nccwpck_require__(30954); - -// src/submodules/cbor/CborCodec.ts -var import_schema = __nccwpck_require__(41320); -var import_serde3 = __nccwpck_require__(98520); -var import_util_base64 = __nccwpck_require__(82763); -var CborCodec = class { - createSerializer() { - const serializer = new CborShapeSerializer(); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new CborShapeDeserializer(); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -}; -var CborShapeSerializer = class { - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - write(schema, value) { - this.value = this.serialize(schema, value); - } - /** - * Recursive serializer transform that copies and prepares the user input object - * for CBOR serialization. - */ - serialize(schema, source) { - const ns = import_schema.NormalizedSchema.of(schema); - if (source == null) { - if (ns.isIdempotencyToken()) { - return (0, import_serde3.generateIdempotencyToken)(); - } - return source; - } - if (ns.isBlobSchema()) { - if (typeof source === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(source); - } - return source; - } - if (ns.isTimestampSchema()) { - if (typeof source === "number" || typeof source === "bigint") { - return dateToTag(new Date(Number(source) / 1e3 | 0)); - } - return dateToTag(source); - } - if (typeof source === "function" || typeof source === "object") { - const sourceObject = source; - if (ns.isListSchema() && Array.isArray(sourceObject)) { - const sparse = !!ns.getMergedTraits().sparse; - const newArray = []; - let i = 0; - for (const item of sourceObject) { - const value = this.serialize(ns.getValueSchema(), item); - if (value != null || sparse) { - newArray[i++] = value; - } - } - return newArray; - } - if (sourceObject instanceof Date) { - return dateToTag(sourceObject); - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - for (const key of Object.keys(sourceObject)) { - const value = this.serialize(ns.getValueSchema(), sourceObject[key]); - if (value != null || sparse) { - newObject[key] = value; - } - } - } else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - const value = this.serialize(memberSchema, sourceObject[key]); - if (value != null) { - newObject[key] = value; - } - } - } else if (ns.isDocumentSchema()) { - for (const key of Object.keys(sourceObject)) { - newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); - } - } - return newObject; - } - return source; - } - flush() { - const buffer = cbor.serialize(this.value); - this.value = void 0; - return buffer; - } -}; -var CborShapeDeserializer = class { - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(schema, bytes) { - const data2 = cbor.deserialize(bytes); - return this.readValue(schema, data2); - } - /** - * Public because it's called by the protocol implementation to deserialize errors. - * @internal - */ - readValue(_schema, value) { - const ns = import_schema.NormalizedSchema.of(_schema); - if (ns.isTimestampSchema() && typeof value === "number") { - return (0, import_serde3.parseEpochTimestamp)(value); - } - if (ns.isBlobSchema()) { - if (typeof value === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(value); - } - return value; - } - if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") { - return value; - } else if (typeof value === "function" || typeof value === "object") { - if (value === null) { - return null; - } - if ("byteLength" in value) { - return value; - } - if (value instanceof Date) { - return value; - } - if (ns.isDocumentSchema()) { - return value; - } - if (ns.isListSchema()) { - const newArray = []; - const memberSchema = ns.getValueSchema(); - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - const itemValue = this.readValue(memberSchema, item); - if (itemValue != null || sparse) { - newArray.push(itemValue); - } - } - return newArray; - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const targetSchema = ns.getValueSchema(); - for (const key of Object.keys(value)) { - const itemValue = this.readValue(targetSchema, value[key]); - if (itemValue != null || sparse) { - newObject[key] = itemValue; - } - } - } else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - newObject[key] = this.readValue(memberSchema, value[key]); - } - } - return newObject; - } else { - return value; - } - } -}; - -// src/submodules/cbor/SmithyRpcV2CborProtocol.ts -var SmithyRpcV2CborProtocol = class extends import_protocols2.RpcProtocol { - constructor({ defaultNamespace }) { - super({ defaultNamespace }); - this.codec = new CborCodec(); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - } - getShapeId() { - return "smithy.protocols#rpcv2Cbor"; - } - getPayloadCodec() { - return this.codec; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - Object.assign(request.headers, { - "content-type": this.getDefaultContentType(), - "smithy-protocol": "rpc-v2-cbor", - accept: this.getDefaultContentType() - }); - if ((0, import_schema2.deref)(operationSchema.input) === "unit") { - delete request.body; - delete request.headers["content-type"]; - } else { - if (!request.body) { - this.serializer.write(15, {}); - request.body = this.serializer.flush(); - } - try { - request.headers["content-length"] = String(request.body.byteLength); - } catch (e) { - } - } - const { service, operation } = (0, import_util_middleware.getSmithyContext)(context); - const path = `/service/${service}/operation/${operation}`; - if (request.path.endsWith("/")) { - request.path += path.slice(1); - } else { - request.path += path; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - if (errorName.includes("#")) { - [namespace] = errorName.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $response: response, - $fault: response.statusCode <= 500 ? "client" : "server" - }; - const registry = import_schema2.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorName); - } catch (e) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; - } - const baseExceptionSchema = import_schema2.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); - } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); - } - const ns = import_schema2.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } - getDefaultContentType() { - return "application/cbor"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 97505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/event-streams/index.ts -var index_exports = {}; -__export(index_exports, { - EventStreamSerde: () => EventStreamSerde -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/event-streams/EventStreamSerde.ts -var import_schema = __nccwpck_require__(41320); -var import_util_utf8 = __nccwpck_require__(85339); -var EventStreamSerde = class { - /** - * Properties are injected by the HttpProtocol. - */ - constructor({ - marshaller, - serializer, - deserializer, - serdeContext, - defaultContentType - }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; - } - for await (const page of eventStream) { - yield page; - } - } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( - unionMember, - unionSchema, - event - ); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream for the end-user. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) - }; - } else { - return { - $unknown: event - }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; - } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error( - "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." - ); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } - } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; - } - } - }; - } - /** - * @param unionMember - member name within the structure that contains an event stream union. - * @param unionSchema - schema of the union. - * @param event - * - * @returns the event body (bytes) and event type (string). - */ - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = unionSchema.hasMemberSchema(unionMember); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(import_schema.SCHEMA.DOCUMENT, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; - } - } - } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } else { - serializer.write(eventSchema, event[unionMember]); - } - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); - } - } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 86752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/protocols/index.ts -var index_exports = {}; -__export(index_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(71914); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; - -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(41320); -var import_serde = __nccwpck_require__(98520); -var import_protocol_http2 = __nccwpck_require__(13494); -var import_util_stream2 = __nccwpck_require__(71914); - -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(41320); -var import_protocol_http = __nccwpck_require__(13494); -var HttpProtocol = class { - constructor(options) { - this.options = options; - } - getRequestType() { - return import_protocol_http.HttpRequest; - } - getResponseType() { - return import_protocol_http.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; - } - } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } - } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }); - } - /** - * Loads eventStream capability async (for chunking). - */ - async loadEventStreamCapability() { - const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(97505))); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); - } - /** - * @returns content-type default header value for event stream events and other documents. - */ - getDefaultContentType() { - throw new Error( - `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` - ); - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - void schema; - void context; - void response; - void arg4; - void arg5; - return []; - } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); - } - return context.eventStreamMarshaller; - } -}; - -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } - } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); - } - } else { - payload = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; - } - } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; - } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); - } - } - return; - } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); - } - } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); - } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; - } - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; - } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - valueSchema, - value - ); - } - } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); - } - } - return nonHttpBindingMembers; - } -}; - -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(41320); -var import_protocol_http3 = __nccwpck_require__(13494); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input - }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); - } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest - }); - } - } else { - serializer.write(schema, _input); - payload = serializer.flush(); - } - } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject - }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } -}; - -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(13494); - -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath2; -}; - -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; - } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); - } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); - } - /** - * Brevity setter for "hostname". - */ - hn(hostname) { - this.hostname = hostname; - return this; - } - /** - * Brevity initial builder for "basepath". - */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; - } - /** - * Brevity incremental builder for "path". - */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; - } - /** - * Brevity setter for "headers". - */ - h(headers) { - this.headers = headers; - return this; - } - /** - * Brevity setter for "query". - */ - q(query) { - this.query = query; - return this; - } - /** - * Brevity setter for "body". - */ - b(body) { - this.body = body; - return this; - } - /** - * Brevity setter for "method". - */ - m(method) { - this.method = method; - return this; - } -}; - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(41320); -var import_serde2 = __nccwpck_require__(98520); -var import_util_base64 = __nccwpck_require__(82763); -var import_util_utf8 = __nccwpck_require__(85339); - -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(41320); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } - } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; - } - return data; - } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); - } -}; - -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(41320); -var import_util_utf82 = __nccwpck_require__(85339); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; - } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; - } - } - return this.codecDeserializer.read(ns, data); - } -}; - -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(41320); - -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(41320); -var import_serde3 = __nccwpck_require__(98520); -var import_util_base642 = __nccwpck_require__(82763); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( - true - )}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); - } - } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; - } -}; - -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; - } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; - } - return this.codecSerializer.flush(); - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 41320: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/schema/index.ts -var index_exports = {}; -__export(index_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); - } - return schemaRef; -}; - -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(13494); -var import_util_middleware = __nccwpck_require__(30954); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, - { - ...config, - ...context - }, - response - ); - return { - response, - output: parsed - }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { - } - } - throw error2; - } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; - -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(30954); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; - -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSchemaSerdePlugin(config) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - } - }; -} - -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - } - static { - this.registries = /* @__PURE__ */ new Map(); - } - /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. - */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. - */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); - } - /** - * @param shapeId - query. - * @returns the schema. - */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. - */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; - } - } - return void 0; - } - /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. - */ - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - /** - * Unloads the current TypeRegistry. - */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; - } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; - } -}; - -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - static assign(instance, values) { - const schema = Object.assign(instance, values); - TypeRegistry.for(schema.namespace).register(schema.name, schema); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; - } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } -}; - -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/lis"); - } -}; -var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema -}); - -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/map"); - } -}; -var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema -}); - -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class _OperationSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _OperationSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/ope"); - } -}; -var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output -}); - -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _StructureSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/str"); - } -}; -var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList -}); - -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor() { - super(...arguments); - this.symbol = _ErrorSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/err"); - } -}; -var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor -}); - -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 -}; - -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _SimpleSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/sim"); - } -}; -var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef -}); - -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { - /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. - */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; - } - if (schema instanceof _NormalizedSchema) { - Object.assign(this, schema); - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; - } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; - } - this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); - } - } - static { - this.symbol = Symbol.for("@smithy/nor"); - } - static [Symbol.hasInstance](lhs) { - return Schema[Symbol.hasInstance].bind(this)(lhs); - } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref) { - if (ref instanceof _NormalizedSchema) { - return ref; - } - if (Array.isArray(ref)) { - const [ns, traits] = ref; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); - return ns; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); - } - return new _NormalizedSchema(ref); - } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; - } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i++ & 1) === 1) { - traits[trait] = 1; - } - } - return traits; - } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - Object.assign(this, { schema: this.schema.getSchema() }); - return this.schema; - } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); - } - return deref(this.schema); - } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; - } - } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); - } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; - } - return inner instanceof ListSchema; - } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; - } - return inner instanceof MapSchema; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; - } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; - } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; - } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; - } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; - } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; - } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; - } - return this.getSchema() === SCHEMA.STREAMING_BLOB; - } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; - } - return false; - } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() - }); - } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); - } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); - } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); - } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); - } - const schema = this.getSchema(); - if (typeof schema === "number") { - return this.memberFrom([63 & schema, 0], "key"); - } - return this.memberFrom([schema.keySchema, 0], "key"); - } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return this.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([63 & schema, 0], "member"); - } - } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); - } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return this.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([collection.valueSchema, 0], "member"); - } - } - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); - } - /** - * @param member - to query. - * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). - */ - hasMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - return struct2.memberNames.includes(member); - } - return false; - } - /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. - */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!struct2.memberNames.includes(member)) { - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); - } - const i = struct2.memberNames.indexOf(member); - const memberSchema = struct2.memberList[i]; - return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], member); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); - } - /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @deprecated use (checked) structIterator instead. - * - * @returns a map of member names to member schemas (normalized). - */ - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; - } - } catch (ignored) { - } - return buffer; - } - /** - * @returns member name of event stream or empty string indicating none exists or this - * isn't a structure schema. - */ - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; - } - } - } - return ""; - } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); - } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; - } - } - /** - * Creates a normalized member schema from the given schema and member name. - */ - memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); - } - return new _NormalizedSchema(memberSchema, memberName); - } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } - } - return "Unknown"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 98520: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/serde/index.ts -var index_exports = {}; -__export(index_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; - -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); - } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -var parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}; -var logger = { - warn: console.warn -}; - -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}; -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); -}; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; -}; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); - } - return input; -}; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; -}; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; - } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); - } -}; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; - } - return strictParseFloat32("0." + value) * 1e3; -}; -var parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); -}; - -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(12048); - -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - } - }); - return str; -}; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); - } - return LazyJsonString(JSON.stringify(object)); -}; -LazyJsonString.fromObject = LazyJsonString.from; - -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} - -// src/submodules/serde/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; -} - -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - default: - } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; - } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); - } - return v.replace(/\\"/g, '"'); - }); -}; - -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); - } - dot = 1; - continue; - } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); - } - } - } - toString() { - return this.string; - } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; - } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); - if (prototypeMatch) { - return prototypeMatch; - } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { - return true; - } - return prototypeMatch; - } -}; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 47299: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(index_exports); - -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(13494); -var import_querystring_builder = __nccwpck_require__(51346); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(82763); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 67908: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8131: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointFromConfig = void 0; -const node_config_provider_1 = __nccwpck_require__(61814); -const getEndpointUrlConfig_1 = __nccwpck_require__(75974); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; - - -/***/ }), - -/***/ 75974: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = __nccwpck_require__(93438); -const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; -const CONFIG_ENDPOINT_URL = "endpoint_url"; -const getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env) => { - const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); - const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - configFileSelector: (profile, config) => { - if (config && profile.services) { - const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); - const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl) - return endpointUrl; - } - } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; - - -/***/ }), - -/***/ 88205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - endpointMiddleware: () => endpointMiddleware, - endpointMiddlewareOptions: () => endpointMiddlewareOptions, - getEndpointFromInstructions: () => getEndpointFromInstructions, - getEndpointPlugin: () => getEndpointPlugin, - resolveEndpointConfig: () => resolveEndpointConfig, - resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, - resolveParams: () => resolveParams, - toEndpointV1: () => toEndpointV1 -}); -module.exports = __toCommonJS(index_exports); - -// src/service-customizations/s3.ts -var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); - } - } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { - endpointParams.ForcePathStyle = true; - } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; - } - return endpointParams; -}, "resolveParamsForS3"); -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); - } - return isValidArn; -}, "isArnBucketName"); - -// src/adaptors/createConfigValueProvider.ts -var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { - const configProvider = /* @__PURE__ */ __name(async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); - } - return configValue; - }, "configProvider"); - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config.isCustomEndpoint === false) { - return void 0; - } - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname, port, path } = endpoint; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; - } - } - return endpoint; - }; - } - return configProvider; -}, "createConfigValueProvider"); - -// src/adaptors/getEndpointFromInstructions.ts -var import_getEndpointFromConfig = __nccwpck_require__(8131); - -// src/adaptors/toEndpointV1.ts -var import_url_parser = __nccwpck_require__(85792); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return (0, import_url_parser.parseUrl)(endpoint.url); - } - return endpoint; - } - return (0, import_url_parser.parseUrl)(endpoint); -}, "toEndpointV1"); - -// src/adaptors/getEndpointFromInstructions.ts -var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); - } else { - endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); - } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; - } - } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); - } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}, "getEndpointFromInstructions"); -var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); - break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); - break; - default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); - } - } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; -}, "resolveParams"); - -// src/endpointMiddleware.ts -var import_core = __nccwpck_require__(22744); -var import_util_middleware = __nccwpck_require__(30954); -var endpointMiddleware = /* @__PURE__ */ __name(({ - config, - instructions -}) => { - return (next, context) => async (args) => { - if (config.isCustomEndpoint) { - (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); - } - const endpoint = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; - } - }, - { ...config }, - context - ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign( - httpAuthOption.signingProperties || {}, - { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet - }, - authScheme.properties - ); - } - } - return next({ - ...args - }); - }; -}, "endpointMiddleware"); - -// src/getEndpointPlugin.ts -var import_middleware_serde = __nccwpck_require__(58305); -var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - endpointMiddleware({ - config, - instructions - }), - endpointMiddlewareOptions - ); - }, "applyToStack") -}), "getEndpointPlugin"); - -// src/resolveEndpointConfig.ts - -var import_getEndpointFromConfig2 = __nccwpck_require__(8131); -var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), - useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) - }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); - } - return configuredEndpointPromise; - }; - return resolvedConfig; -}, "resolveEndpointConfig"); - -// src/resolveEndpointRequiredConfig.ts -var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - throw new Error( - "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." - ); - }; - } - return input; -}, "resolveEndpointRequiredConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 58305: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption -}); -module.exports = __toCommonJS(index_exports); - -// src/deserializerMiddleware.ts -var import_protocol_http = __nccwpck_require__(13494); -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { - } - } - throw error; - } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); - -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); - -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: /* @__PURE__ */ __name((commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, "applyToStack") - }; -} -__name(getSerdePlugin, "getSerdePlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 61814: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/configLoader.ts - - -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(1104); - -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } -} -__name(getSelectorName, "getSelectorName"); - -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); - } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); - } -}, "fromEnv"); - -// src/fromSharedConfigFiles.ts - -var import_shared_ini_file_loader = __nccwpck_require__(93438); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); - } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); - -// src/fromStatic.ts - -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); - -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 95493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(index_exports); - -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(13494); -var import_querystring_builder = __nccwpck_require__(51346); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") -}; - -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} -__name(writeBody, "writeBody"); - -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - static { - __name(this, "NodeHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/node-http2-handler.ts - - -var import_http22 = __nccwpck_require__(85675); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); - -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - static { - __name(this, "NodeHttp2ConnectionPool"); - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } - } -}; - -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } - static { - __name(this, "NodeHttp2ConnectionManager"); - } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); - } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } -}; - -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); - } - static { - __name(this, "NodeHttp2Handler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } -}; - -// src/stream-collector/collector.ts - -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } -}; - -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1104: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); - -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; - -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; - -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 13494: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = __nccwpck_require__(50892); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; - -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; - } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); - } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } -}; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 51346: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(72644); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 18352: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseQueryString: () => parseQueryString -}); -module.exports = __toCommonJS(index_exports); -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; - } - } - } - return query; -} -__name(parseQueryString, "parseQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 91690: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; - - -/***/ }), - -/***/ 66531: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(91690); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; - - -/***/ }), - -/***/ 83280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(66531); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; - - -/***/ }), - -/***/ 93438: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(91690), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(66531), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(83280); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(50892); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(91690); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(91690); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(91690); - -// src/parseIni.ts - -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } - } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(95016); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(95016); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); - -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } - } - } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); - -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(83280); -var import_slurpFile3 = __nccwpck_require__(95016); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 95016: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; - - -/***/ }), - -/***/ 50892: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 85792: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseUrl: () => parseUrl -}); -module.exports = __toCommonJS(index_exports); -var import_querystring_parser = __nccwpck_require__(18352); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1724: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(40037); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); - } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); - } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); -}; -exports.fromBase64 = fromBase64; - - -/***/ }), - -/***/ 82763: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(1724), module.exports); -__reExport(index_exports, __nccwpck_require__(99617), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 99617: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(40037); -const util_utf8_1 = __nccwpck_require__(85339); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } - else { - input = _input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); - } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 84916: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(index_exports); - -// src/calculateBodyLength.ts -var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (typeof body === "string") { - if (TEXT_ENCODER) { - return TEXT_ENCODER.encode(body).byteLength; - } - let len = body.length; - for (let i = len - 1; i >= 0; i--) { - const code = body.charCodeAt(i); - if (code > 127 && code <= 2047) len++; - else if (code > 2047 && code <= 65535) len += 2; - if (code >= 56320 && code <= 57343) i--; - } - return len; - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; - } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 40037: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(67908); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 70397: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 30954: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(50892); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 96338: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; - } -} -exports.ByteArrayCollector = ByteArrayCollector; - - -/***/ }), - -/***/ 73787: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 13821: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(82763); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); - } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); - } -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 17227: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(82763); -const stream_type_check_1 = __nccwpck_require__(68604); -const ChecksumStream_browser_1 = __nccwpck_require__(73787); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; -}; -exports.createChecksumStream = createChecksumStream; - - -/***/ }), - -/***/ 5869: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(68604); -const ChecksumStream_1 = __nccwpck_require__(13821); -const createChecksumStream_browser_1 = __nccwpck_require__(17227); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} - - -/***/ }), - -/***/ 77523: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(96338); -const createBufferedReadableStream_1 = __nccwpck_require__(55971); -const stream_type_check_1 = __nccwpck_require__(68604); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; -} - - -/***/ }), - -/***/ 55971: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(96338); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; - } - return -1; -} - - -/***/ }), - -/***/ 25024: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; - - -/***/ }), - -/***/ 46916: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; -} - - -/***/ }), - -/***/ 66922: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(46916); -const stream_type_check_1 = __nccwpck_require__(68604); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); -}; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; - } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } -} - - -/***/ }), - -/***/ 71914: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter -}); -module.exports = __toCommonJS(index_exports); - -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(82763); -var import_util_utf8 = __nccwpck_require__(85339); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { - static { - __name(this, "Uint8ArrayBlobAdapter"); - } - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); - } -}; - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(13821), module.exports); -__reExport(index_exports, __nccwpck_require__(5869), module.exports); -__reExport(index_exports, __nccwpck_require__(77523), module.exports); -__reExport(index_exports, __nccwpck_require__(25024), module.exports); -__reExport(index_exports, __nccwpck_require__(66922), module.exports); -__reExport(index_exports, __nccwpck_require__(51027), module.exports); -__reExport(index_exports, __nccwpck_require__(39346), module.exports); -__reExport(index_exports, __nccwpck_require__(68604), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 60445: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(47299); -const util_base64_1 = __nccwpck_require__(82763); -const util_hex_encoding_1 = __nccwpck_require__(70397); -const util_utf8_1 = __nccwpck_require__(85339); -const stream_type_check_1 = __nccwpck_require__(68604); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 51027: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(95493); -const util_buffer_from_1 = __nccwpck_require__(40037); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(60445); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), - -/***/ 70988: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); -} - - -/***/ }), - -/***/ 39346: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(70988); -const stream_type_check_1 = __nccwpck_require__(68604); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); - } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} - - -/***/ }), - -/***/ 68604: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; - - -/***/ }), - -/***/ 72644: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 85339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(index_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(40037); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 62041: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8704); -const util_middleware_1 = __nccwpck_require__(26252); -const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccountRoles": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccounts": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "Logout": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; +const checkState$2 = async (client, input) => { + let reason; + try { + const result = await client.send(new DescribeServicesCommand(input)); + reason = result; + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.failures); + const projection_3 = flat_1.map((element_2) => { + return element_2.reason; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "MISSING") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + catch (e) { } + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.services); + const projection_3 = flat_1.map((element_2) => { + return element_2.status; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "DRAINING") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } } - } - return options; -}; -exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 13903: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(83068); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(41308); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 41308: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 62054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, - GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, - GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, - InvalidRequestException: () => InvalidRequestException, - ListAccountRolesCommand: () => ListAccountRolesCommand, - ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, - ListAccountsCommand: () => ListAccountsCommand, - ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, - LogoutCommand: () => LogoutCommand, - LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, - ResourceNotFoundException: () => ResourceNotFoundException, - RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, - SSO: () => SSO, - SSOClient: () => SSOClient, - SSOServiceException: () => SSOServiceException, - TooManyRequestsException: () => TooManyRequestsException, - UnauthorizedException: () => UnauthorizedException, - __Client: () => import_smithy_client.Client, - paginateListAccountRoles: () => paginateListAccountRoles, - paginateListAccounts: () => paginateListAccounts -}); -module.exports = __toCommonJS(index_exports); - -// src/SSOClient.ts -var import_middleware_host_header = __nccwpck_require__(52590); -var import_middleware_logger = __nccwpck_require__(85242); -var import_middleware_recursion_detection = __nccwpck_require__(81568); -var import_middleware_user_agent = __nccwpck_require__(32959); -var import_config_resolver = __nccwpck_require__(39316); -var import_core = __nccwpck_require__(3402); -var import_middleware_content_length = __nccwpck_require__(47212); -var import_middleware_endpoint = __nccwpck_require__(88075); -var import_middleware_retry = __nccwpck_require__(19618); - -var import_httpAuthSchemeProvider = __nccwpck_require__(62041); - -// src/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/SSOClient.ts -var import_runtimeConfig = __nccwpck_require__(82696); - -// src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(36463); -var import_protocol_http = __nccwpck_require__(46572); -var import_smithy_client = __nccwpck_require__(61411); - -// src/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/SSOClient.ts -var SSOClient = class extends import_smithy_client.Client { - static { - __name(this, "SSOClient"); - } - /** - * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/SSO.ts - - -// src/commands/GetRoleCredentialsCommand.ts - -var import_middleware_serde = __nccwpck_require__(4783); - - -// src/models/models_0.ts - - -// src/models/SSOServiceException.ts - -var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "SSOServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOServiceException.prototype); - } -}; - -// src/models/models_0.ts -var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - } -}; -var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { - static { - __name(this, "ResourceNotFoundException"); - } - name = "ResourceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } -}; -var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { - static { - __name(this, "TooManyRequestsException"); - } - name = "TooManyRequestsException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsException.prototype); - } -}; -var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { - static { - __name(this, "UnauthorizedException"); - } - name = "UnauthorizedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedException.prototype); - } + catch (e) { } + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.services); + const projection_3 = flat_1.map((element_2) => { + return element_2.status; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "INACTIVE") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } + } + catch (e) { } + try { + const returnComparator = () => { + const filterRes_2 = result.services.filter((element_1) => { + return !(element_1.deployments.length == 1.0 && element_1.runningCount == element_1.desiredCount); + }); + return filterRes_2.length == 0.0; + }; + if (returnComparator() == true) { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + catch (e) { } + } + catch (exception) { + reason = exception; + } + return { state: utilWaiter.WaiterState.RETRY, reason }; }; -var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "GetRoleCredentialsRequestFilterSensitiveLog"); -var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, - ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } -}), "RoleCredentialsFilterSensitiveLog"); -var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } -}), "GetRoleCredentialsResponseFilterSensitiveLog"); -var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountRolesRequestFilterSensitiveLog"); -var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountsRequestFilterSensitiveLog"); -var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "LogoutRequestFilterSensitiveLog"); - -// src/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(8704); - - -var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/federation/credentials"); - const query = (0, import_smithy_client.map)({ - [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_GetRoleCredentialsCommand"); -var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/roles"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountRolesCommand"); -var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/accounts"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountsCommand"); -var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/logout"); - let body; - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_LogoutCommand"); -var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - roleCredentials: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_GetRoleCredentialsCommand"); -var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - nextToken: import_smithy_client.expectString, - roleList: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountRolesCommand"); -var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - accountList: import_smithy_client._json, - nextToken: import_smithy_client.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountsCommand"); -var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - await (0, import_smithy_client.collectBody)(output.body, context); - return contents; -}, "de_LogoutCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); - switch (errorCode) { - case "InvalidRequestException": - case "com.amazonaws.sso#InvalidRequestException": - throw await de_InvalidRequestExceptionRes(parsedOutput, context); - case "ResourceNotFoundException": - case "com.amazonaws.sso#ResourceNotFoundException": - throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); - case "TooManyRequestsException": - case "com.amazonaws.sso#TooManyRequestsException": - throw await de_TooManyRequestsExceptionRes(parsedOutput, context); - case "UnauthorizedException": - case "com.amazonaws.sso#UnauthorizedException": - throw await de_UnauthorizedExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody, - errorCode - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new ResourceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_ResourceNotFoundExceptionRes"); -var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new TooManyRequestsException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_TooManyRequestsExceptionRes"); -var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); -var _aI = "accountId"; -var _aT = "accessToken"; -var _ai = "account_id"; -var _mR = "maxResults"; -var _mr = "max_result"; -var _nT = "nextToken"; -var _nt = "next_token"; -var _rN = "roleName"; -var _rn = "role_name"; -var _xasbt = "x-amz-sso_bearer_token"; - -// src/commands/GetRoleCredentialsCommand.ts -var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { - static { - __name(this, "GetRoleCredentialsCommand"); - } +const waitForServicesStable = async (params, input) => { + const serviceDefaults = { minDelay: 15, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); }; - -// src/commands/ListAccountRolesCommand.ts - - - -var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { - static { - __name(this, "ListAccountRolesCommand"); - } +const waitUntilServicesStable = async (params, input) => { + const serviceDefaults = { minDelay: 15, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); + return utilWaiter.checkExceptions(result); }; -// src/commands/ListAccountsCommand.ts - - - -var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { - static { - __name(this, "ListAccountsCommand"); - } +const checkState$1 = async (client, input) => { + let reason; + try { + const result = await client.send(new DescribeTasksCommand(input)); + reason = result; + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.tasks); + const projection_3 = flat_1.map((element_2) => { + return element_2.lastStatus; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "STOPPED") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } + } + catch (e) { } + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.failures); + const projection_3 = flat_1.map((element_2) => { + return element_2.reason; + }); + return projection_3; + }; + for (const anyStringEq_4 of returnComparator()) { + if (anyStringEq_4 == "MISSING") { + return { state: utilWaiter.WaiterState.FAILURE, reason }; + } + } + } + catch (e) { } + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.tasks); + const projection_3 = flat_1.map((element_2) => { + return element_2.lastStatus; + }); + return projection_3; + }; + let allStringEq_5 = returnComparator().length > 0; + for (const element_4 of returnComparator()) { + allStringEq_5 = allStringEq_5 && element_4 == "RUNNING"; + } + if (allStringEq_5) { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + catch (e) { } + } + catch (exception) { + reason = exception; + } + return { state: utilWaiter.WaiterState.RETRY, reason }; }; - -// src/commands/LogoutCommand.ts - - - -var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { - static { - __name(this, "LogoutCommand"); - } +const waitForTasksRunning = async (params, input) => { + const serviceDefaults = { minDelay: 6, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); +}; +const waitUntilTasksRunning = async (params, input) => { + const serviceDefaults = { minDelay: 6, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); + return utilWaiter.checkExceptions(result); }; -// src/SSO.ts -var commands = { - GetRoleCredentialsCommand, - ListAccountRolesCommand, - ListAccountsCommand, - LogoutCommand +const checkState = async (client, input) => { + let reason; + try { + const result = await client.send(new DescribeTasksCommand(input)); + reason = result; + try { + const returnComparator = () => { + const flat_1 = [].concat(...result.tasks); + const projection_3 = flat_1.map((element_2) => { + return element_2.lastStatus; + }); + return projection_3; + }; + let allStringEq_5 = returnComparator().length > 0; + for (const element_4 of returnComparator()) { + allStringEq_5 = allStringEq_5 && element_4 == "STOPPED"; + } + if (allStringEq_5) { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + catch (e) { } + } + catch (exception) { + reason = exception; + } + return { state: utilWaiter.WaiterState.RETRY, reason }; }; -var SSO = class extends SSOClient { - static { - __name(this, "SSO"); - } +const waitForTasksStopped = async (params, input) => { + const serviceDefaults = { minDelay: 6, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); +}; +const waitUntilTasksStopped = async (params, input) => { + const serviceDefaults = { minDelay: 6, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); + return utilWaiter.checkExceptions(result); }; -(0, import_smithy_client.createAggregatedClient)(commands, SSO); - -// src/pagination/ListAccountRolesPaginator.ts - -var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListAccountsPaginator.ts - -var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +Object.defineProperty(exports, "$Command", ({ + enumerable: true, + get: function () { return smithyClient.Command; } +})); +Object.defineProperty(exports, "__Client", ({ + enumerable: true, + get: function () { return smithyClient.Client; } +})); +exports.AcceleratorManufacturer = AcceleratorManufacturer; +exports.AcceleratorName = AcceleratorName; +exports.AcceleratorType = AcceleratorType; +exports.AccessDeniedException = AccessDeniedException; +exports.AgentUpdateStatus = AgentUpdateStatus; +exports.ApplicationProtocol = ApplicationProtocol; +exports.AssignPublicIp = AssignPublicIp; +exports.AttributeLimitExceededException = AttributeLimitExceededException; +exports.AvailabilityZoneRebalancing = AvailabilityZoneRebalancing; +exports.BareMetal = BareMetal; +exports.BlockedException = BlockedException; +exports.BurstablePerformance = BurstablePerformance; +exports.CPUArchitecture = CPUArchitecture; +exports.CapacityProviderField = CapacityProviderField; +exports.CapacityProviderStatus = CapacityProviderStatus; +exports.CapacityProviderType = CapacityProviderType; +exports.CapacityProviderUpdateStatus = CapacityProviderUpdateStatus; +exports.ClientException = ClientException; +exports.ClusterContainsCapacityProviderException = ClusterContainsCapacityProviderException; +exports.ClusterContainsContainerInstancesException = ClusterContainsContainerInstancesException; +exports.ClusterContainsServicesException = ClusterContainsServicesException; +exports.ClusterContainsTasksException = ClusterContainsTasksException; +exports.ClusterField = ClusterField; +exports.ClusterNotFoundException = ClusterNotFoundException; +exports.ClusterSettingName = ClusterSettingName; +exports.Compatibility = Compatibility; +exports.ConflictException = ConflictException; +exports.Connectivity = Connectivity; +exports.ContainerCondition = ContainerCondition; +exports.ContainerInstanceField = ContainerInstanceField; +exports.ContainerInstanceStatus = ContainerInstanceStatus; +exports.CpuManufacturer = CpuManufacturer; +exports.CreateCapacityProviderCommand = CreateCapacityProviderCommand; +exports.CreateClusterCommand = CreateClusterCommand; +exports.CreateServiceCommand = CreateServiceCommand; +exports.CreateTaskSetCommand = CreateTaskSetCommand; +exports.DeleteAccountSettingCommand = DeleteAccountSettingCommand; +exports.DeleteAttributesCommand = DeleteAttributesCommand; +exports.DeleteCapacityProviderCommand = DeleteCapacityProviderCommand; +exports.DeleteClusterCommand = DeleteClusterCommand; +exports.DeleteServiceCommand = DeleteServiceCommand; +exports.DeleteTaskDefinitionsCommand = DeleteTaskDefinitionsCommand; +exports.DeleteTaskSetCommand = DeleteTaskSetCommand; +exports.DeploymentControllerType = DeploymentControllerType; +exports.DeploymentLifecycleHookStage = DeploymentLifecycleHookStage; +exports.DeploymentRolloutState = DeploymentRolloutState; +exports.DeploymentStrategy = DeploymentStrategy; +exports.DeregisterContainerInstanceCommand = DeregisterContainerInstanceCommand; +exports.DeregisterTaskDefinitionCommand = DeregisterTaskDefinitionCommand; +exports.DescribeCapacityProvidersCommand = DescribeCapacityProvidersCommand; +exports.DescribeClustersCommand = DescribeClustersCommand; +exports.DescribeContainerInstancesCommand = DescribeContainerInstancesCommand; +exports.DescribeServiceDeploymentsCommand = DescribeServiceDeploymentsCommand; +exports.DescribeServiceRevisionsCommand = DescribeServiceRevisionsCommand; +exports.DescribeServicesCommand = DescribeServicesCommand; +exports.DescribeTaskDefinitionCommand = DescribeTaskDefinitionCommand; +exports.DescribeTaskSetsCommand = DescribeTaskSetsCommand; +exports.DescribeTasksCommand = DescribeTasksCommand; +exports.DesiredStatus = DesiredStatus; +exports.DeviceCgroupPermission = DeviceCgroupPermission; +exports.DiscoverPollEndpointCommand = DiscoverPollEndpointCommand; +exports.EBSResourceType = EBSResourceType; +exports.ECS = ECS; +exports.ECSClient = ECSClient; +exports.ECSServiceException = ECSServiceException; +exports.EFSAuthorizationConfigIAM = EFSAuthorizationConfigIAM; +exports.EFSTransitEncryption = EFSTransitEncryption; +exports.EnvironmentFileType = EnvironmentFileType; +exports.ExecuteCommandCommand = ExecuteCommandCommand; +exports.ExecuteCommandLogging = ExecuteCommandLogging; +exports.ExecuteCommandResponseFilterSensitiveLog = ExecuteCommandResponseFilterSensitiveLog; +exports.FirelensConfigurationType = FirelensConfigurationType; +exports.GetTaskProtectionCommand = GetTaskProtectionCommand; +exports.HealthStatus = HealthStatus; +exports.InstanceGeneration = InstanceGeneration; +exports.InstanceHealthCheckState = InstanceHealthCheckState; +exports.InstanceHealthCheckType = InstanceHealthCheckType; +exports.InvalidParameterException = InvalidParameterException; +exports.IpcMode = IpcMode; +exports.LaunchType = LaunchType; +exports.LimitExceededException = LimitExceededException; +exports.ListAccountSettingsCommand = ListAccountSettingsCommand; +exports.ListAttributesCommand = ListAttributesCommand; +exports.ListClustersCommand = ListClustersCommand; +exports.ListContainerInstancesCommand = ListContainerInstancesCommand; +exports.ListServiceDeploymentsCommand = ListServiceDeploymentsCommand; +exports.ListServicesByNamespaceCommand = ListServicesByNamespaceCommand; +exports.ListServicesCommand = ListServicesCommand; +exports.ListTagsForResourceCommand = ListTagsForResourceCommand; +exports.ListTaskDefinitionFamiliesCommand = ListTaskDefinitionFamiliesCommand; +exports.ListTaskDefinitionsCommand = ListTaskDefinitionsCommand; +exports.ListTasksCommand = ListTasksCommand; +exports.LocalStorage = LocalStorage; +exports.LocalStorageType = LocalStorageType; +exports.LogDriver = LogDriver; +exports.ManagedAgentName = ManagedAgentName; +exports.ManagedDraining = ManagedDraining; +exports.ManagedInstancesMonitoringOptions = ManagedInstancesMonitoringOptions; +exports.ManagedScalingStatus = ManagedScalingStatus; +exports.ManagedTerminationProtection = ManagedTerminationProtection; +exports.MissingVersionException = MissingVersionException; +exports.NamespaceNotFoundException = NamespaceNotFoundException; +exports.NetworkMode = NetworkMode; +exports.NoUpdateAvailableException = NoUpdateAvailableException; +exports.OSFamily = OSFamily; +exports.PidMode = PidMode; +exports.PlacementConstraintType = PlacementConstraintType; +exports.PlacementStrategyType = PlacementStrategyType; +exports.PlatformDeviceType = PlatformDeviceType; +exports.PlatformTaskDefinitionIncompatibilityException = PlatformTaskDefinitionIncompatibilityException; +exports.PlatformUnknownException = PlatformUnknownException; +exports.PropagateMITags = PropagateMITags; +exports.PropagateTags = PropagateTags; +exports.ProxyConfigurationType = ProxyConfigurationType; +exports.PutAccountSettingCommand = PutAccountSettingCommand; +exports.PutAccountSettingDefaultCommand = PutAccountSettingDefaultCommand; +exports.PutAttributesCommand = PutAttributesCommand; +exports.PutClusterCapacityProvidersCommand = PutClusterCapacityProvidersCommand; +exports.RegisterContainerInstanceCommand = RegisterContainerInstanceCommand; +exports.RegisterTaskDefinitionCommand = RegisterTaskDefinitionCommand; +exports.ResourceInUseException = ResourceInUseException; +exports.ResourceNotFoundException = ResourceNotFoundException; +exports.ResourceType = ResourceType; +exports.RunTaskCommand = RunTaskCommand; +exports.ScaleUnit = ScaleUnit; +exports.SchedulingStrategy = SchedulingStrategy; +exports.Scope = Scope; +exports.ServerException = ServerException; +exports.ServiceDeploymentLifecycleStage = ServiceDeploymentLifecycleStage; +exports.ServiceDeploymentNotFoundException = ServiceDeploymentNotFoundException; +exports.ServiceDeploymentRollbackMonitorsStatus = ServiceDeploymentRollbackMonitorsStatus; +exports.ServiceDeploymentStatus = ServiceDeploymentStatus; +exports.ServiceField = ServiceField; +exports.ServiceNotActiveException = ServiceNotActiveException; +exports.ServiceNotFoundException = ServiceNotFoundException; +exports.SessionFilterSensitiveLog = SessionFilterSensitiveLog; +exports.SettingName = SettingName; +exports.SettingType = SettingType; +exports.SortOrder = SortOrder; +exports.StabilityStatus = StabilityStatus; +exports.StartTaskCommand = StartTaskCommand; +exports.StopServiceDeploymentCommand = StopServiceDeploymentCommand; +exports.StopServiceDeploymentStopType = StopServiceDeploymentStopType; +exports.StopTaskCommand = StopTaskCommand; +exports.SubmitAttachmentStateChangesCommand = SubmitAttachmentStateChangesCommand; +exports.SubmitContainerStateChangeCommand = SubmitContainerStateChangeCommand; +exports.SubmitTaskStateChangeCommand = SubmitTaskStateChangeCommand; +exports.TagResourceCommand = TagResourceCommand; +exports.TargetNotConnectedException = TargetNotConnectedException; +exports.TargetNotFoundException = TargetNotFoundException; +exports.TargetType = TargetType; +exports.TaskDefinitionFamilyStatus = TaskDefinitionFamilyStatus; +exports.TaskDefinitionField = TaskDefinitionField; +exports.TaskDefinitionPlacementConstraintType = TaskDefinitionPlacementConstraintType; +exports.TaskDefinitionStatus = TaskDefinitionStatus; +exports.TaskField = TaskField; +exports.TaskFilesystemType = TaskFilesystemType; +exports.TaskSetField = TaskSetField; +exports.TaskSetNotFoundException = TaskSetNotFoundException; +exports.TaskStopCode = TaskStopCode; +exports.TransportProtocol = TransportProtocol; +exports.UlimitName = UlimitName; +exports.UnsupportedFeatureException = UnsupportedFeatureException; +exports.UntagResourceCommand = UntagResourceCommand; +exports.UpdateCapacityProviderCommand = UpdateCapacityProviderCommand; +exports.UpdateClusterCommand = UpdateClusterCommand; +exports.UpdateClusterSettingsCommand = UpdateClusterSettingsCommand; +exports.UpdateContainerAgentCommand = UpdateContainerAgentCommand; +exports.UpdateContainerInstancesStateCommand = UpdateContainerInstancesStateCommand; +exports.UpdateInProgressException = UpdateInProgressException; +exports.UpdateServiceCommand = UpdateServiceCommand; +exports.UpdateServicePrimaryTaskSetCommand = UpdateServicePrimaryTaskSetCommand; +exports.UpdateTaskProtectionCommand = UpdateTaskProtectionCommand; +exports.UpdateTaskSetCommand = UpdateTaskSetCommand; +exports.VersionConsistency = VersionConsistency; +exports.paginateListAccountSettings = paginateListAccountSettings; +exports.paginateListAttributes = paginateListAttributes; +exports.paginateListClusters = paginateListClusters; +exports.paginateListContainerInstances = paginateListContainerInstances; +exports.paginateListServices = paginateListServices; +exports.paginateListServicesByNamespace = paginateListServicesByNamespace; +exports.paginateListTaskDefinitionFamilies = paginateListTaskDefinitionFamilies; +exports.paginateListTaskDefinitions = paginateListTaskDefinitions; +exports.paginateListTasks = paginateListTasks; +exports.waitForServicesInactive = waitForServicesInactive; +exports.waitForServicesStable = waitForServicesStable; +exports.waitForTasksRunning = waitForTasksRunning; +exports.waitForTasksStopped = waitForTasksStopped; +exports.waitUntilServicesInactive = waitUntilServicesInactive; +exports.waitUntilServicesStable = waitUntilServicesStable; +exports.waitUntilTasksRunning = waitUntilTasksRunning; +exports.waitUntilTasksStopped = waitUntilTasksStopped; /***/ }), -/***/ 82696: +/***/ 41142: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -39489,17 +22172,18 @@ var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccou Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(45188)); -const core_1 = __nccwpck_require__(8704); -const util_user_agent_node_1 = __nccwpck_require__(51656); +const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(51194)); +const core_1 = __nccwpck_require__(91446); +const credential_provider_node_1 = __nccwpck_require__(60395); +const util_user_agent_node_1 = __nccwpck_require__(9082); const config_resolver_1 = __nccwpck_require__(39316); const hash_node_1 = __nccwpck_require__(5092); const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(50240); -const node_http_handler_1 = __nccwpck_require__(60967); +const node_config_provider_1 = __nccwpck_require__(61814); +const node_http_handler_1 = __nccwpck_require__(95493); const util_body_length_node_1 = __nccwpck_require__(13638); const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(8073); +const runtimeConfig_shared_1 = __nccwpck_require__(31519); const smithy_client_1 = __nccwpck_require__(61411); const util_defaults_mode_node_1 = __nccwpck_require__(15435); const smithy_client_2 = __nccwpck_require__(61411); @@ -39520,6 +22204,7 @@ const getRuntimeConfig = (config) => { defaultsMode, authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, defaultUserAgentProvider: config?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), @@ -39543,44 +22228,38 @@ exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 8073: +/***/ 31519: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8704); -const core_2 = __nccwpck_require__(3402); +const core_1 = __nccwpck_require__(91446); const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(38006); -const util_base64_1 = __nccwpck_require__(76249); -const util_utf8_1 = __nccwpck_require__(55969); -const httpAuthSchemeProvider_1 = __nccwpck_require__(62041); -const endpointResolver_1 = __nccwpck_require__(13903); +const url_parser_1 = __nccwpck_require__(85792); +const util_base64_1 = __nccwpck_require__(82763); +const util_utf8_1 = __nccwpck_require__(85339); +const httpAuthSchemeProvider_1 = __nccwpck_require__(1367); +const endpointResolver_1 = __nccwpck_require__(6161); const getRuntimeConfig = (config) => { return { - apiVersion: "2019-06-10", + apiVersion: "2014-11-13", base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, disableHostPrefix: config?.disableHostPrefix ?? false, endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultECSHttpAuthSchemeProvider, httpAuthSchemes: config?.httpAuthSchemes ?? [ { schemeId: "aws.auth#sigv4", identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), signer: new core_1.AwsSdkSigV4Signer(), }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, ], logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO", + serviceId: config?.serviceId ?? "ECS", urlParser: config?.urlParser ?? url_parser_1.parseUrl, utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, @@ -39589,720 +22268,2270 @@ const getRuntimeConfig = (config) => { exports.getRuntimeConfig = getRuntimeConfig; -/***/ }), +/***/ }), + +/***/ 91446: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var protocolHttp = __nccwpck_require__(13494); +var core = __nccwpck_require__(22744); +var propertyProvider = __nccwpck_require__(1104); +var client = __nccwpck_require__(17582); +var signatureV4 = __nccwpck_require__(75118); +var cbor = __nccwpck_require__(91467); +var schema = __nccwpck_require__(41320); +var protocols = __nccwpck_require__(86752); +var serde = __nccwpck_require__(98520); +var utilBase64 = __nccwpck_require__(82763); +var smithyClient = __nccwpck_require__(61411); +var utilUtf8 = __nccwpck_require__(85339); +var xmlBuilder = __nccwpck_require__(2344); + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/74kJMmI`); + } +}; + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const resolveAwsSdkSigV4Config = (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = core.normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => core.normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await core.normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + }); + return resolvedConfig; +}; +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +class ProtocolLib { + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } + else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } + else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } + else { + return defaultContentType; + } + } + else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let namespace = defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $response: response, + $fault: response.statusCode < 500 ? "client" : "server", + }; + const registry = schema.TypeRegistry.for(namespace); + try { + const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } + catch (e) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== undefined && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const entries = Object.entries(output); + const Error = { + Code, + Type, + }; + Object.assign(output, Error); + for (const [k, v] of entries) { + Error[k] = v; + } + delete Error.__type; + output.Error = Error; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } +} -/***/ 3402: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin = new ProtocolLib(); + constructor({ defaultNamespace, awsQueryCompatible, }) { + super({ defaultNamespace }); + this.awsQueryCompatible = !!awsQueryCompatible; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = cbor.loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema.namespace).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +const _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase !== "false"; + } + return val; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(42394); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(26252); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; - } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } +const _toNum = (val) => { + if (val == null) { + return val; } - } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; } - } - return preferredAuthOptions; -}, "resolveAuthOptions"); + return val; +}; -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); - } - return map; +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } } -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new serde.NumericValue(numericString, "bigDecimal"); + } + else { + return BigInt(numericString); + } + } + } } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; + return value; +} + +const collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body)); + +const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer + return {}; +}); +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadRestJsonErrorCode = (output, data) => { + const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } + } }; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(4783); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemePlugin"); +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + return this._read(schema, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema$1, value) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._read(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._read(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const deserializedValue = this._read(memberSchema, value[fromKey]); + if (deserializedValue != null) { + out[memberName] = deserializedValue; + } + } + return out; + } + if (ns.isBlobSchema() && typeof value === "string") { + return utilBase64.fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + if (ns.isTimestampSchema() && value != null) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return serde.parseRfc3339DateTimeWithOffset(value); + case 6: + return serde.parseRfc7231DateTime(value); + case 7: + return serde.parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof serde.NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new serde.NumericValue(untyped.string, untyped.type); + } + return new serde.NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(46572); +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof serde.NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + this.rootSchema = schema.NormalizedSchema.of(schema$1); + this.buffer = this._write(this.rootSchema, value); + } + writeDiscriminatedDocument(schema$1, value) { + this.write(schema$1, value); + if (typeof this.buffer === "object") { + this.buffer.__type = schema.NormalizedSchema.of(schema$1).getName(true); + } + } + flush() { + const { rootSchema } = this; + this.rootSchema = undefined; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + _write(schema$1, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const serializableValue = this._write(memberSchema, value[memberName], ns); + if (serializableValue !== undefined) { + out[targetKey] = serializableValue; + } + } + return out; + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if ((ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) || + (ns.isDocumentSchema() && value instanceof Uint8Array)) { + if (ns === this.rootSchema) { + return value; + } + if (!this.serdeContext?.base64Encoder) { + return utilBase64.toBase64(value); + } + return this.serdeContext?.base64Encoder(value); + } + if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return serde.dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (ns.isNumericSchema() && typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return serde.generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return serde.LazyJsonString.from(value); + } + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof serde.NumericValue) { + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" -}; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); - }, "applyToStack") -}), "getHttpSigningPlugin"); +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsJsonRpcProtocol extends protocols.RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin = new ProtocolLib(); + awsQueryCompatible; + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + }); + this.serviceTarget = serviceTarget; + this.codec = new JsonCodec({ + timestampFormat: { + useTrait: true, + default: 7, + }, + jsonName: false, + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": `${this.serviceTarget}.${schema.NormalizedSchema.of(operationSchema).getName()}`, + }); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema.namespace).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } +} -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); +class AwsJson1_0Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } +} -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); +class AwsJson1_1Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; } - return void 0; - }, "paginateOperation"); } -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; + +class AwsRestJsonProtocol extends protocols.HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace }) { + super({ + defaultNamespace, + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7, + }, + httpBindings: true, + jsonName: true, + }; + this.codec = new JsonCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.headers["content-type"] && !request.body) { + request.body = "{}"; + } + return request; } - cursor = cursor[step]; - } - return cursor; -}, "get"); + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema.namespace).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/json"; + } +} -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(50678); +const awsExpectUnion = (value) => { + if (value == null) { + return undefined; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return smithyClient.expectUnion(value); +}; -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; - } - context.__smithy_context.features[feature] = value; +class XmlShapeDeserializer extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema$1, bytes, key) { + const ns = schema.NormalizedSchema.of(schema$1); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && + ns.isMemberSchema() && + !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } + else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const sparse = !!traits.sparse; + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + if (v != null || sparse) { + buffer.push(this.readSchema(listValue, v)); + } + } + return buffer; + } + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } + else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value = entry[valueProperty]; + if (value != null || sparse) { + buffer[key] = this.readSchema(memberNs, value); + } + } + return buffer; + } + if (ns.isStructSchema()) { + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload + ? memberSchema.getMemberTraits().xmlName ?? memberName + : memberTraits.xmlName ?? memberSchema.getName(); + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(xml); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; + } } -__name(setFeature, "setFeature"); -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } +class QueryShapeSerializer extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; } - } - static { - __name(this, "DefaultIdentityProviderConfig"); - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { - static { - __name(this, "HttpApiKeyAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); + write(schema$1, value, prefix = "") { + if (this.buffer === undefined) { + this.buffer = ""; + } + const ns = schema.NormalizedSchema.of(schema$1); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value)); + } + } + else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue(serde.generateIdempotencyToken()); + } + } + else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof serde.NumericValue ? value.string : String(value)); + } + } + else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue(smithyClient.dateToUtcString(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1000)); + break; + } + } + } + else if (ns.isDocumentSchema()) { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); + } + else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } + else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const suffix = this.getKey("member", member.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } + else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const [k, v] of Object.entries(value)) { + if (v == null) { + continue; + } + const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } + else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + } + } + } + else if (ns.isUnitSchema()) ; + else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + flush() { + if (this.buffer === undefined) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + getKey(memberName, xmlName) { + const key = xmlName ?? memberName; + if (this.settings.capitalizeKeys) { + return key[0].toUpperCase() + key.slice(1); + } + return key; } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`; } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); + writeValue(value) { + this.buffer += protocols.extendedEncodeURIComponent(value); } - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts +} -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); +class AwsQueryProtocol extends protocols.RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true, + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; - } -}; - -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); + getShapeId() { + return "aws.protocols#awsQuery"; } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); } - if (isConstant) { - return resolved; + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-www-form-urlencoded`, + }); + if (schema.deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; + const bytes = await protocols.collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject, + }; + return output; } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; + useNestedResult() { + return true; } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + const errorData = this.loadQueryError(dataObject); + const message = this.loadQueryErrorMessage(dataObject); + errorData.message = message; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message, + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, (registry, errorName) => registry.find((schema$1) => schema.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName)); + const ns = schema.NormalizedSchema.of(errorSchema); + const ErrorCtor = schema.TypeRegistry.for(errorSchema.namespace).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + const output = { + Error: errorData.Error, + }; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); } - return resolved; - }; -}, "memoizeIdentityProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== undefined) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } +} -/***/ 94747: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +class AwsEc2QueryProtocol extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + }; + Object.assign(this.serializer.settings, ec2Settings); + } + useNestedResult() { + return false; + } +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = xmlBuilder.parseXML(encoded); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return smithyClient.getValueFromTextNode(parsedObjToReturn); + } + return {}; +}); +const parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const loadRestXmlErrorCode = (output, data) => { + if (data?.Error?.Code !== undefined) { + return data.Error.Code; + } + if (data?.Code !== undefined) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/event-streams/index.ts -var index_exports = {}; -__export(index_exports, { - EventStreamSerde: () => EventStreamSerde -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/event-streams/EventStreamSerde.ts -var import_schema = __nccwpck_require__(52290); -var import_util_utf8 = __nccwpck_require__(55969); -var EventStreamSerde = class { - /** - * Properties are injected by the HttpProtocol. - */ - constructor({ - marshaller, - serializer, - deserializer, - serdeContext, - defaultContentType - }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; +class XmlShapeSerializer extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; } - for await (const page of eventStream) { - yield page; + else if (ns.isBlobSchema()) { + this.byteBuffer = + "byteLength" in value + ? value + : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); } - } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( - unionMember, - unionSchema, - event - ); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream for the end-user. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) + else { + this.buffer = this.writeStruct(ns, value, undefined); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== undefined) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== undefined) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload + ? ns.getMemberTraits().xmlName ?? ns.getMemberName() + : traits.xmlName ?? ns.getName(); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = xmlBuilder.XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } + else { + const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); + } + else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container, xmlns); + } + else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); + } + else { + const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container.addChildNode(listItemNode); + } }; - } else { - return { - $unknown: event + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } + else { + const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = xmlBuilder.XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = xmlBuilder.XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } + else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } + else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } + else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; - } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error( - "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." - ); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } + if (flat) { + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } + else { + let mapNode; + if (!containerIsMap) { + mapNode = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = xmlBuilder.XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; + const ns = schema.NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + } + else if (ns.isTimestampSchema() && value instanceof Date) { + const format = protocols.determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = smithyClient.dateToUtcString(value); + break; + case 7: + nodeContents = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = smithyClient.dateToUtcString(value); + break; + } + } + else if (ns.isBigDecimalSchema() && value) { + if (value instanceof serde.NumericValue) { + return value.string; + } + return String(value); + } + else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } + else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } } - } - }; - } - /** - * @param unionMember - member name within the structure that contains an event stream union. - * @param unionSchema - schema of the union. - * @param event - * - * @returns the event body (bytes) and event type (string). - */ - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = unionSchema.hasMemberSchema(unionMember); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(import_schema.SCHEMA.DOCUMENT, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === undefined && ns.isIdempotencyToken()) { + nodeContents = serde.generateIdempotencyToken(); + } + else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = schema.NormalizedSchema.of(_schema); + const content = new xmlBuilder.XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } +} + +class XmlCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsRestXmlProtocol extends protocols.HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + }; + this.codec = new XmlCodec(settings); + this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = schema.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; + } + if (request.headers["content-type"] === this.getDefaultContentType()) { + if (typeof request.body === "string") { + request.body = '' + request.body; } - } } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } else { - serializer.write(eventSchema, event[unionMember]); + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = schema.NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; + const ErrorCtor = schema.TypeRegistry.for(errorSchema.namespace).getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = this.codec.createDeserializer().readSchema(member, value); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/xml"; + } +} + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; +exports.AwsJson1_0Protocol = AwsJson1_0Protocol; +exports.AwsJson1_1Protocol = AwsJson1_1Protocol; +exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; +exports.AwsQueryProtocol = AwsQueryProtocol; +exports.AwsRestJsonProtocol = AwsRestJsonProtocol; +exports.AwsRestXmlProtocol = AwsRestXmlProtocol; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.XmlCodec = XmlCodec; +exports.XmlShapeDeserializer = XmlShapeDeserializer; +exports.XmlShapeSerializer = XmlShapeSerializer; +exports._toBool = _toBool; +exports._toNum = _toNum; +exports._toStr = _toStr; +exports.awsExpectUnion = awsExpectUnion; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadRestXmlErrorCode = loadRestXmlErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.parseXmlBody = parseXmlBody; +exports.parseXmlErrorBody = parseXmlErrorBody; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setTokenFeature = setTokenFeature; +exports.state = state; +exports.validateSigningProperties = validateSigningProperties; + + +/***/ }), + +/***/ 17582: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/74kJMmI`); + } +}; + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setTokenFeature = setTokenFeature; +exports.state = state; + + +/***/ }), + +/***/ 56104: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var client = __nccwpck_require__(17582); +var propertyProvider = __nccwpck_require__(1104); + +const ENV_KEY = "AWS_ACCESS_KEY_ID"; +const ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; +const ENV_SESSION = "AWS_SESSION_TOKEN"; +const ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; +const ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; +const ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; +const fromEnv = (init) => async () => { + init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...(sessionToken && { sessionToken }), + ...(expiry && { expiration: new Date(expiry) }), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + client.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; + } + throw new propertyProvider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); +}; + +exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; +exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; +exports.ENV_EXPIRATION = ENV_EXPIRATION; +exports.ENV_KEY = ENV_KEY; +exports.ENV_SECRET = ENV_SECRET; +exports.ENV_SESSION = ENV_SESSION; +exports.fromEnv = fromEnv; + + +/***/ }), + +/***/ 60395: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var credentialProviderEnv = __nccwpck_require__(56104); +var propertyProvider = __nccwpck_require__(1104); +var sharedIniFileLoader = __nccwpck_require__(93438); + +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const remoteProvider = async (init) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve(/* import() */).then(__nccwpck_require__.t.bind(__nccwpck_require__, 40566, 19)); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = await __nccwpck_require__.e(/* import() */ 795).then(__nccwpck_require__.bind(__nccwpck_require__, 60795)); + return propertyProvider.chain(fromHttp(init), fromContainerMetadata(init)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new propertyProvider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); + }; + } + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init); +}; + +let multipleCredentialSourceWarningEmitted = false; +const defaultProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(async () => { + const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" + ? init.logger.warn.bind(init.logger) + : console.warn; + warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +`); + multipleCredentialSourceWarningEmitted = true; + } } - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); - } + throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init.logger, + tryNextLink: true, + }); } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return credentialProviderEnv.fromEnv(init)(); +}, async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger }); + } + const { fromSSO } = await __nccwpck_require__.e(/* import() */ 212).then(__nccwpck_require__.t.bind(__nccwpck_require__, 8212, 19)); + return fromSSO(init)(); +}, async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await __nccwpck_require__.e(/* import() */ 163).then(__nccwpck_require__.t.bind(__nccwpck_require__, 26163, 19)); + return fromIni(init)(); +}, async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await __nccwpck_require__.e(/* import() */ 630).then(__nccwpck_require__.t.bind(__nccwpck_require__, 15630, 19)); + return fromProcess(init)(); +}, async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await Promise.all(/* import() */[__nccwpck_require__.e(58), __nccwpck_require__.e(654)]).then(__nccwpck_require__.t.bind(__nccwpck_require__, 47654, 23)); + return fromTokenFile(init)(); +}, async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); +}, async () => { + throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger, + }); +}), credentialsTreatedAsExpired, credentialsWillNeedRefresh); +const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined; +const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; + +exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; +exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; +exports.defaultProvider = defaultProvider; + + +/***/ }), + +/***/ 25164: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getHostHeaderPlugin: () => getHostHeaderPlugin, + hostHeaderMiddleware: () => hostHeaderMiddleware, + hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, + resolveHostHeaderConfig: () => resolveHostHeaderConfig +}); +module.exports = __toCommonJS(index_exports); +var import_protocol_http = __nccwpck_require__(13494); +function resolveHostHeaderConfig(input) { + return input; +} +__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); +var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) host += `:${request.port}`; + request.headers["host"] = host; } + return next(args); +}, "hostHeaderMiddleware"); +var hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true }; +var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, "applyToStack") +}), "getHostHeaderPlugin"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 50678: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 65832: +/***/ ((module) => { + +"use strict"; -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -40315,911 +24544,1032 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath + getLoggerPlugin: () => getLoggerPlugin, + loggerMiddleware: () => loggerMiddleware, + loggerMiddlewareOptions: () => loggerMiddlewareOptions }); module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(64356); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); +// src/loggerMiddleware.ts +var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata + }); + return response; + } catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata + }); + throw error; } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}, "loggerMiddleware"); +var loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true }; +var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, "applyToStack") +}), "getLoggerPlugin"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} +0 && (0); -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(52290); -var import_serde = __nccwpck_require__(24054); -var import_protocol_http2 = __nccwpck_require__(46572); -var import_util_stream2 = __nccwpck_require__(64356); -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(52290); -var import_protocol_http = __nccwpck_require__(46572); -var HttpProtocol = class { - constructor(options) { - this.options = options; - } - getRequestType() { - return import_protocol_http.HttpRequest; - } - getResponseType() { - return import_protocol_http.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } + +/***/ }), + +/***/ 39870: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getRecursionDetectionPlugin: () => getRecursionDetectionPlugin +}); +module.exports = __toCommonJS(index_exports); + +// src/configuration.ts +var recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" +}; + +// src/getRecursionDetectionPlugin.ts +var import_recursionDetectionMiddleware = __nccwpck_require__(6971); +var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add((0, import_recursionDetectionMiddleware.recursionDetectionMiddleware)(), recursionDetectionMiddlewareOptions); + }, "applyToStack") +}), "getRecursionDetectionPlugin"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(6971), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 6971: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.recursionDetectionMiddleware = void 0; +const lambda_invoke_store_1 = __nccwpck_require__(37453); +const protocol_http_1 = __nccwpck_require__(13494); +const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; +const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; +const recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!protocol_http_1.HttpRequest.isInstance(request)) { + return next(args); } - } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? + TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); } - } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }); - } - /** - * Loads eventStream capability async (for chunking). - */ - async loadEventStreamCapability() { - const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(94747))); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); - } - /** - * @returns content-type default header value for event stream events and other documents. - */ - getDefaultContentType() { - throw new Error( - `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` - ); - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - void schema; - void context; - void response; - void arg4; - void arg5; - return []; - } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[ENV_TRACE_ID]; + const traceIdFromInvokeStore = lambda_invoke_store_1.InvokeStore.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; } - return context.eventStreamMarshaller; - } + return next({ + ...args, + request, + }); }; +exports.recursionDetectionMiddleware = recursionDetectionMiddleware; -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } + +/***/ }), + +/***/ 70997: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var core = __nccwpck_require__(22744); +var utilEndpoints = __nccwpck_require__(16158); +var protocolHttp = __nccwpck_require__(13494); +var core$1 = __nccwpck_require__(91446); + +const DEFAULT_UA_APP_ID = undefined; +function isValidUserAgentAppId(appId) { + if (appId === undefined) { + return true; } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); + return typeof appId === "string" && appId.length <= 50; +} +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } + else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, + }); +} + +const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + core$1.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + core$1.setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); + } + else { + core$1.setFeature(context, "RETRY_MODE_STANDARD", "E"); } - } else { - payload = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; - } - } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; - } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); + else { + core$1.setFeature(context, "RETRY_MODE_LEGACY", "D"); } - } - return; } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + core$1.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); } - } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); - } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + core$1.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + core$1.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + core$1.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; } - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + core$1.setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - valueSchema, - value - ); - } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + core$1.setFeature(context, key, value); } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); - } } - return nonHttpBindingMembers; - } -}; +} -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(52290); -var import_protocol_http3 = __nccwpck_require__(46572); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input - }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); +const USER_AGENT = "user-agent"; +const X_AMZ_USER_AGENT = "x-amz-user-agent"; +const SPACE = " "; +const UA_NAME_SEPARATOR = "/"; +const UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; +const UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; +const UA_ESCAPE_CHAR = "-"; + +const BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest - }); + else { + buffer += val; + } + continue; } - } else { - serializer.write(schema, _input); - payload = serializer.flush(); - } + break; } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + return buffer; +} + +const userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!protocolHttp.HttpRequest.isInstance(request)) { + return next(args); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + } + const prefix = utilEndpoints.getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []) + .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) + .join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent, + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] + ? `${headers[USER_AGENT]} ${normalUAValue}` + : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject - }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } + else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; + return next({ + ...args, + request, + }); +}; +const escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0] + .split(UA_NAME_SEPARATOR) + .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)) + .join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version] + .filter((item) => item && item.length > 0) + .reduce((acc, item, index) => { + switch (index) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); +}; +const getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true, +}; +const getUserAgentPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, +}); + +exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; +exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; +exports.getUserAgentPlugin = getUserAgentPlugin; +exports.resolveUserAgentConfig = resolveUserAgentConfig; +exports.userAgentMiddleware = userAgentMiddleware; + + +/***/ }), + +/***/ 26521: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(46572); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, + REGION_ENV_NAME: () => REGION_ENV_NAME, + REGION_INI_NAME: () => REGION_INI_NAME, + getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, + resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, + resolveRegionConfig: () => resolveRegionConfig +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); +// src/extensions/index.ts +var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); + }; +}, "getAwsRegionExtensionConfiguration"); +var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; +}, "resolveAwsRegionExtensionConfiguration"); + +// src/regionConfig/config.ts +var REGION_ENV_NAME = "AWS_REGION"; +var REGION_INI_NAME = "region"; +var NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), + default: /* @__PURE__ */ __name(() => { + throw new Error("Region is missing"); + }, "default") +}; +var NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials" +}; + +// src/regionConfig/isFipsRegion.ts +var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); + +// src/regionConfig/getRealRegion.ts +var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); + +// src/regionConfig/resolveRegionConfig.ts +var resolveRegionConfig = /* @__PURE__ */ __name((input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: /* @__PURE__ */ __name(async () => { + if (typeof region === "string") { + return getRealRegion(region); + } + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, "region"), + useFipsEndpoint: /* @__PURE__ */ __name(async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, "useFipsEndpoint") + }); +}, "resolveRegionConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 16158: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return resolvedPath2; + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; - } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + ConditionObject: () => import_util_endpoints.ConditionObject, + DeprecatedObject: () => import_util_endpoints.DeprecatedObject, + EndpointError: () => import_util_endpoints.EndpointError, + EndpointObject: () => import_util_endpoints.EndpointObject, + EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, + EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, + EndpointParams: () => import_util_endpoints.EndpointParams, + EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, + EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, + ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, + EvaluateOptions: () => import_util_endpoints.EvaluateOptions, + Expression: () => import_util_endpoints.Expression, + FunctionArgv: () => import_util_endpoints.FunctionArgv, + FunctionObject: () => import_util_endpoints.FunctionObject, + FunctionReturn: () => import_util_endpoints.FunctionReturn, + ParameterObject: () => import_util_endpoints.ParameterObject, + ReferenceObject: () => import_util_endpoints.ReferenceObject, + ReferenceRecord: () => import_util_endpoints.ReferenceRecord, + RuleSetObject: () => import_util_endpoints.RuleSetObject, + RuleSetRules: () => import_util_endpoints.RuleSetRules, + TreeRuleObject: () => import_util_endpoints.TreeRuleObject, + awsEndpointFunctions: () => awsEndpointFunctions, + getUserAgentPrefix: () => getUserAgentPrefix, + isIpAddress: () => import_util_endpoints.isIpAddress, + partition: () => partition, + resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, + resolveEndpoint: () => import_util_endpoints.resolveEndpoint, + setPartitionInfo: () => setPartitionInfo, + toEndpointV1: () => toEndpointV1, + useDefaultPartitionInfo: () => useDefaultPartitionInfo +}); +module.exports = __toCommonJS(index_exports); + +// src/aws.ts + + +// src/lib/aws/isVirtualHostableS3Bucket.ts + + +// src/lib/isIpAddress.ts +var import_util_endpoints = __nccwpck_require__(79674); + +// src/lib/aws/isVirtualHostableS3Bucket.ts +var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); - } - /** - * Brevity setter for "hostname". - */ - hn(hostname) { - this.hostname = hostname; - return this; - } - /** - * Brevity initial builder for "basepath". - */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; - } - /** - * Brevity incremental builder for "path". - */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + return true; } - /** - * Brevity setter for "headers". - */ - h(headers) { - this.headers = headers; - return this; + if (!(0, import_util_endpoints.isValidHostLabel)(value)) { + return false; } - /** - * Brevity setter for "query". - */ - q(query) { - this.query = query; - return this; + if (value.length < 3 || value.length > 63) { + return false; } - /** - * Brevity setter for "body". - */ - b(body) { - this.body = body; - return this; + if (value !== value.toLowerCase()) { + return false; } - /** - * Brevity setter for "method". - */ - m(method) { - this.method = method; - return this; + if ((0, import_util_endpoints.isIpAddress)(value)) { + return false; } -}; + return true; +}, "isVirtualHostableS3Bucket"); -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(52290); -var import_serde2 = __nccwpck_require__(24054); -var import_util_base64 = __nccwpck_require__(76249); -var import_util_utf8 = __nccwpck_require__(55969); +// src/lib/aws/parseArn.ts +var ARN_DELIMITER = ":"; +var RESOURCE_DELIMITER = "/"; +var parseArn = /* @__PURE__ */ __name((value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) return null; + const [arn, partition2, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region, + accountId, + resourceId + }; +}, "parseArn"); -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(52290); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); +// src/lib/aws/partitions.json +var partitions_default = { + partitions: [{ + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); + }, { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); + }, { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" } } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); - } - return intermediateValue; + }, { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" } } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; + }, { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + }], + version: "1.1" +}; + +// src/lib/aws/partition.ts +var selectedPartitionsInfo = partitions_default; +var selectedUserAgentPrefix = ""; +var partition = /* @__PURE__ */ __name((value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition2 of partitions) { + const { regions, outputs } = partition2; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } + } + } + for (const partition2 of partitions) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; } - return data; } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error( + "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist." + ); } + return { + ...DEFAULT_PARTITION.outputs + }; +}, "partition"); +var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}, "setPartitionInfo"); +var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { + setPartitionInfo(partitions_default, ""); +}, "useDefaultPartitionInfo"); +var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); + +// src/aws.ts +var awsEndpointFunctions = { + isVirtualHostableS3Bucket, + parseArn, + partition }; +import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(52290); -var import_util_utf82 = __nccwpck_require__(55969); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; +// src/resolveDefaultAwsRegionalEndpointsConfig.ts +var import_url_parser = __nccwpck_require__(85792); +var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; - } - } - return this.codecDeserializer.read(ns, data); + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + return toEndpointV1( + input.endpointProvider( + { + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: void 0 + }, + { logger: input.logger } + ) + ); + }; } + return input; +}, "resolveDefaultAwsRegionalEndpointsConfig"); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); + +// src/resolveEndpoint.ts + + +// src/types/EndpointError.ts + + +// src/types/EndpointRuleObject.ts + + +// src/types/ErrorRuleObject.ts + + +// src/types/RuleSetObject.ts + + +// src/types/TreeRuleObject.ts + + +// src/types/shared.ts + +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 9082: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var os = __nccwpck_require__(70857); +var process = __nccwpck_require__(932); +var middlewareUserAgent = __nccwpck_require__(70997); + +const crtAvailability = { + isCrtAvailable: false, }; -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(52290); +const isCrtAvailable = () => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}; -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(52290); -var import_serde3 = __nccwpck_require__(24054); -var import_util_base642 = __nccwpck_require__(76249); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( - true - )}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; +const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => { + return async (config) => { + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${os.platform()}`, os.release()], + ["lang/js"], + ["md/nodejs", `${process.versions.node}`], + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } + if (process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${process.env.AWS_EXECUTION_ENV}`]); } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); - } - } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; - } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; }; +const defaultUserAgent = createDefaultUserAgentProvider; -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; - } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; - } - return this.codecSerializer.flush(); - } +const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +const UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +const NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME], + configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], + default: middlewareUserAgent.DEFAULT_UA_APP_ID, }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); + +exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS; +exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; +exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; +exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider; +exports.crtAvailability = crtAvailability; +exports.defaultUserAgent = defaultUserAgent; /***/ }), -/***/ 52290: +/***/ 2344: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -41234,3725 +25584,5589 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct + XmlNode: () => XmlNode, + XmlText: () => XmlText, + parseXML: () => import_xml_parser.parseXML }); module.exports = __toCommonJS(index_exports); -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); - } - return schemaRef; -}; - -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(46572); -var import_util_middleware = __nccwpck_require__(26252); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, - { - ...config, - ...context - }, - response - ); - return { - response, - output: parsed - }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { - } - } - throw error2; - } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; +// src/escape-attribute.ts +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +__name(escapeAttribute, "escapeAttribute"); -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(26252); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; +// src/escape-element.ts +function escapeElement(value) { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); +} +__name(escapeElement, "escapeElement"); -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true +// src/XmlText.ts +var XmlText = class { + constructor(value) { + this.value = value; + } + static { + __name(this, "XmlText"); + } + toString() { + return escapeElement("" + this.value); + } }; -function getSchemaSerdePlugin(config) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - } - }; -} -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; +// src/XmlNode.ts +var XmlNode = class _XmlNode { + constructor(name, children = []) { + this.name = name; + this.children = children; } static { - this.registries = /* @__PURE__ */ new Map(); + __name(this, "XmlNode"); + } + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== void 0) { + node.withName(withName); + } + return node; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; } /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. + * @internal + * Alias of {@link XmlNode#withName(string)} for codegen brevity. */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); + n(name) { + this.name = name; + return this; } /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. + * @internal + * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); + c(child) { + this.children.push(child); + return this; } /** - * @param shapeId - query. - * @returns the schema. + * @internal + * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); + a(name, value) { + if (value != null) { + this.attributes[name] = value; } - return this.schemas.get(id); + return this; } /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. + * Create a child node. + * Used in serialization of string fields. + * @internal */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; - } + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); } - return void 0; } /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. + * Creates list child nodes. + * @internal */ - find(predicate) { - return [...this.schemas.values()].find(predicate); + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } } /** - * Unloads the current TypeRegistry. + * Creates list child nodes with container. + * @internal */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); } - return this.namespace + "#" + shapeId; } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; } }; -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - static assign(instance, values) { - const schema = Object.assign(instance, values); - TypeRegistry.for(schema.namespace).register(schema.name, schema); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; +// src/index.ts +var import_xml_parser = __nccwpck_require__(4785); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 4785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseXML = parseXML; +const fast_xml_parser_1 = __nccwpck_require__(50591); +const parser = new fast_xml_parser_1.XMLParser({ + attributeNamePrefix: "", + htmlEntities: true, + ignoreAttributes: false, + ignoreDeclaration: true, + parseTagValue: false, + trimValues: false, + tagValueProcessor: (_, val) => (val.trim() === "" && val.includes("\n") ? "" : undefined), +}); +parser.addEntity("#xD", "\r"); +parser.addEntity("#10", "\n"); +function parseXML(xmlString) { + return parser.parse(xmlString, true); +} + + +/***/ }), + +/***/ 22744: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(50892); +var utilMiddleware = __nccwpck_require__(30954); +var middlewareSerde = __nccwpck_require__(58305); +var protocolHttp = __nccwpck_require__(13494); +var protocols = __nccwpck_require__(86752); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; }; -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/lis"); - } +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; +} +const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = utilMiddleware.getSmithyContext(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); }; -var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema + +const httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware", +}; +const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + }, }); -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/map"); - } -}; -var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema +const httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: middlewareSerde.serializerMiddlewareOption.name, +}; +const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeMiddlewareOptions); + }, }); -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class _OperationSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _OperationSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/ope"); - } +const defaultErrorHandler = (signingProperties) => (error) => { + throw error; +}; +const defaultSuccessHandler = (httpResponse, signingProperties) => { }; +const httpSigningMiddleware = (config) => (next, context) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = utilMiddleware.getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties), + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; }; -var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output -}); -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _StructureSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/str"); - } +const httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware", }; -var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList +const getHttpSigningPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions); + }, }); -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor() { - super(...arguments); - this.symbol = _ErrorSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/err"); - } +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; }; -var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor -}); -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 +const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}; +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); + } + else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return undefined; + }; +} +const get = (fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return undefined; + } + cursor = cursor[step]; + } + return cursor; }; -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _SimpleSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/sim"); - } +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {}, + }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} + +class DefaultIdentityProviderConfig { + authSchemes = new Map(); + constructor(config) { + for (const [key, value] of Object.entries(config)) { + if (value !== undefined) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +} + +class HttpApiKeyAuthSigner { + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); + if (signingProperties.in === types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } + else if (signingProperties.in === types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme + ? `${signingProperties.scheme} ${identity.apiKey}` + : identity.apiKey; + } + else { + throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + + "but found: `" + + signingProperties.in + + "`"); + } + return clonedRequest; + } +} + +class HttpBearerAuthSigner { + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } +} + +class NoAuthSigner { + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +} + +const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; +}; +const EXPIRATION_MS = 300_000; +const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined; +const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === undefined) { + return undefined; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; }; -var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef -}); -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { - /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. - */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; +Object.defineProperty(exports, "requestBuilder", ({ + enumerable: true, + get: function () { return protocols.requestBuilder; } +})); +exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig; +exports.EXPIRATION_MS = EXPIRATION_MS; +exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner; +exports.HttpBearerAuthSigner = HttpBearerAuthSigner; +exports.NoAuthSigner = NoAuthSigner; +exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction; +exports.createPaginator = createPaginator; +exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh; +exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin; +exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin; +exports.getHttpSigningPlugin = getHttpSigningPlugin; +exports.getSmithyContext = getSmithyContext; +exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions; +exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware; +exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions; +exports.httpSigningMiddleware = httpSigningMiddleware; +exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions; +exports.isIdentityExpired = isIdentityExpired; +exports.memoizeIdentityProvider = memoizeIdentityProvider; +exports.normalizeProvider = normalizeProvider; +exports.setFeature = setFeature; + + +/***/ }), + +/***/ 91467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var serde = __nccwpck_require__(98520); +var utilUtf8 = __nccwpck_require__(85339); +var protocols = __nccwpck_require__(86752); +var protocolHttp = __nccwpck_require__(13494); +var utilBodyLengthBrowser = __nccwpck_require__(84916); +var schema = __nccwpck_require__(41320); +var utilMiddleware = __nccwpck_require__(30954); +var utilBase64 = __nccwpck_require__(82763); + +const majorUint64 = 0; +const majorNegativeInt64 = 1; +const majorUnstructuredByteString = 2; +const majorUtf8String = 3; +const majorList = 4; +const majorMap = 5; +const majorTag = 6; +const majorSpecial = 7; +const specialFalse = 20; +const specialTrue = 21; +const specialNull = 22; +const specialUndefined = 23; +const extendedOneByte = 24; +const extendedFloat16 = 25; +const extendedFloat32 = 26; +const extendedFloat64 = 27; +const minorIndefinite = 31; +function alloc(size) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); +} +const tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); +function tag(data) { + data[tagSymbol] = true; + return data; +} + +const USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; +const USE_BUFFER$1 = typeof Buffer !== "undefined"; +let payload = alloc(0); +let dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +const textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; +let _offset = 0; +function setPayload(bytes) { + payload = bytes; + dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } + else { + switch (minor) { + case extendedOneByte: + case extendedFloat16: + case extendedFloat32: + case extendedFloat64: + const countLength = minorValueToArgumentLength[minor]; + const countOffset = (countLength + 1); + offset = countOffset; + if (to - at < countOffset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + unsignedInt = payload[countIndex]; + } + else if (countLength === 2) { + unsignedInt = dataView$1.getUint16(countIndex); + } + else if (countLength === 4) { + unsignedInt = dataView$1.getUint32(countIndex); + } + else { + unsignedInt = dataView$1.getBigUint64(countIndex); + } + break; + default: + throw new Error(`unexpected minor value ${minor}.`); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt(unsignedInt); + } + else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } + else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt(negativeInt); + } + else { + if (minor === 2 || minor === 3) { + const length = decodeCount(at + offset, to); + let b = BigInt(0); + const start = at + offset + _offset; + for (let i = start; i < start + length; ++i) { + b = (b << BigInt(8)) | BigInt(payload[i]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b - BigInt(1) : b; + } + else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [exponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); + let numericString; + const sign = mantissa < 0 ? "-" : ""; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + _offset = offset + _offset; + return serde.nv(numericString); + } + else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt(unsignedInt), value }); + } + } + case majorUtf8String: + case majorMap: + case majorList: + case majorUnstructuredByteString: + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } + else { + switch (major) { + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + } + } + default: + return decodeSpecial(at, to); } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; +} +function bytesToUtf8(bytes, at, to) { + if (USE_BUFFER$1 && bytes.constructor?.name === "Buffer") { + return bytes.toString("utf-8", at, to); } - if (schema instanceof _NormalizedSchema) { - Object.assign(this, schema); - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; + if (textDecoder) { + return textDecoder.decode(bytes.subarray(at, to)); } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; + return utilUtf8.toUtf8(bytes.subarray(at, to)); +} +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); } - this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + return num; +} +const minorValueToArgumentLength = { + [extendedOneByte]: 1, + [extendedFloat16]: 2, + [extendedFloat32]: 4, + [extendedFloat64]: 8, +}; +function bytesToFloat16(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + let exponentComponent; + let summation; + if (exponent === 0b00000) { + if (fraction === 0b00000_00000) { + return 0; + } + else { + exponentComponent = Math.pow(2, 1 - 15); + summation = 0; + } } - } - static { - this.symbol = Symbol.for("@smithy/nor"); - } - static [Symbol.hasInstance](lhs) { - return Schema[Symbol.hasInstance].bind(this)(lhs); - } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref) { - if (ref instanceof _NormalizedSchema) { - return ref; + else if (exponent === 0b11111) { + if (fraction === 0b00000_00000) { + return scalar * Infinity; + } + else { + return NaN; + } } - if (Array.isArray(ref)) { - const [ns, traits] = ref; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); - return ns; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + else { + exponentComponent = Math.pow(2, exponent - 15); + summation = 1; } - return new _NormalizedSchema(ref); - } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; + summation += fraction / 1024; + return scalar * (exponentComponent * summation); +} +function decodeCount(at, to) { + const minor = payload[at] & 0b0001_1111; + if (minor < 24) { + _offset = 1; + return minor; } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i++ & 1) === 1) { - traits[trait] = 1; - } + if (minor === extendedOneByte || + minor === extendedFloat16 || + minor === extendedFloat32 || + minor === extendedFloat64) { + const countLength = minorValueToArgumentLength[minor]; + _offset = (countLength + 1); + if (to - at < _offset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + return payload[countIndex]; + } + else if (countLength === 2) { + return dataView$1.getUint16(countIndex); + } + else if (countLength === 4) { + return dataView$1.getUint32(countIndex); + } + return demote(dataView$1.getBigUint64(countIndex)); } - return traits; - } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - Object.assign(this, { schema: this.schema.getSchema() }); - return this.schema; + throw new Error(`unexpected minor value ${minor}.`); +} +function decodeUtf8String(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`string len ${length} greater than remaining buf len.`); + } + const value = bytesToUtf8(payload, at, at + length); + _offset = offset + length; + return value; +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return bytesToUtf8(data, 0, data.length); + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); + } + const value = payload.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return data; + } + const major = (payload[at] & 0b1110_0000) >> 5; + const minor = payload[at] & 0b0001_1111; + if (major !== majorUnstructuredByteString) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeList(at, to) { + const listDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const list = Array(listDataLength); + for (let i = 0; i < listDataLength; ++i) { + const item = decode(at, to); + const itemOffset = _offset; + list[i] = item; + at += itemOffset; + } + _offset = offset + (at - base); + return list; +} +function decodeListIndefinite(at, to) { + at += 1; + const list = []; + for (const base = at; at < to;) { + if (payload[at] === 0b1111_1111) { + _offset = at - base + 2; + return list; + } + const item = decode(at, to); + const n = _offset; + at += n; + list.push(item); + } + throw new Error("expected break marker."); +} +function decodeMap(at, to) { + const mapDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const map = {}; + for (let i = 0; i < mapDataLength; ++i) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + const major = (payload[at] & 0b1110_0000) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key at index ${at}.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; + } + _offset = offset + (at - base); + return map; +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map = {}; + for (; at < to;) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + if (payload[at] === 0b1111_1111) { + _offset = at - base + 2; + return map; + } + const major = (payload[at] & 0b1110_0000) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; + } + throw new Error("expected break marker."); +} +function decodeSpecial(at, to) { + const minor = payload[at] & 0b0001_1111; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16(payload[at + 1], payload[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView$1.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView$1.getFloat64(at + 1); + default: + throw new Error(`unexpected minor value ${minor}.`); + } +} +function castBigInt(bigInt) { + if (typeof bigInt === "number") { + return bigInt; + } + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} + +const USE_BUFFER = typeof Buffer !== "undefined"; +const initialSize = 2048; +let data = alloc(initialSize); +let dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); +let cursor = 0; +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor; + if (remaining < bytes) { + if (cursor < 16_000_000) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } + else { + resize(data.byteLength + bytes + 16_000_000); + } } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); +} +function toUint8Array() { + const out = alloc(cursor); + out.set(data.subarray(0, cursor), 0); + cursor = 0; + return out; +} +function resize(size) { + const old = data; + data = alloc(size); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } + else { + data.set(old, 0); + } } - return deref(this.schema); - } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; - } + dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeHeader(major, value) { + if (value < 24) { + data[cursor++] = (major << 5) | value; } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + else if (value < 1 << 8) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = value; } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + else if (value < 1 << 16) { + data[cursor++] = (major << 5) | extendedFloat16; + dataView.setUint16(cursor, value); + cursor += 2; } - return inner instanceof ListSchema; - } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + else if (value < 2 ** 32) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, value); + cursor += 4; } - return inner instanceof MapSchema; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; - } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; - } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; - } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; - } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; - } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; - } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; + else { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); + cursor += 8; } - return this.getSchema() === SCHEMA.STREAMING_BLOB; - } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; +} +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + ensureSpace(typeof input === "string" ? input.length * 4 : 64); + if (typeof input === "string") { + if (USE_BUFFER) { + encodeHeader(majorUtf8String, Buffer.byteLength(input)); + cursor += data.write(input, cursor); + } + else { + const bytes = utilUtf8.fromUtf8(input); + encodeHeader(majorUtf8String, bytes.byteLength); + data.set(bytes, cursor); + cursor += bytes.byteLength; + } + continue; + } + else if (typeof input === "number") { + if (Number.isInteger(input)) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = value; + } + else if (value < 65536) { + data[cursor++] = (major << 5) | extendedFloat16; + data[cursor++] = value >> 8; + data[cursor++] = value; + } + else if (value < 4294967296) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, value); + cursor += 4; + } + else { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, BigInt(value)); + cursor += 8; + } + continue; + } + data[cursor++] = (majorSpecial << 5) | extendedFloat64; + dataView.setFloat64(cursor, input); + cursor += 8; + continue; + } + else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + const n = Number(value); + if (n < 24) { + data[cursor++] = (major << 5) | n; + } + else if (n < 256) { + data[cursor++] = (major << 5) | 24; + data[cursor++] = n; + } + else if (n < 65536) { + data[cursor++] = (major << 5) | extendedFloat16; + data[cursor++] = n >> 8; + data[cursor++] = n & 0b1111_1111; + } + else if (n < 4294967296) { + data[cursor++] = (major << 5) | extendedFloat32; + dataView.setUint32(cursor, n); + cursor += 4; + } + else if (value < BigInt("18446744073709551616")) { + data[cursor++] = (major << 5) | extendedFloat64; + dataView.setBigUint64(cursor, value); + cursor += 8; + } + else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b = value; + let i = 0; + while (bigIntBytes.byteLength - ++i >= 0) { + bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2); + data[cursor++] = nonNegative ? 0b110_00010 : 0b110_00011; + if (USE_BUFFER) { + encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); + } + else { + encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); + } + data.set(bigIntBytes, cursor); + cursor += bigIntBytes.byteLength; + } + continue; + } + else if (input === null) { + data[cursor++] = (majorSpecial << 5) | specialNull; + continue; + } + else if (typeof input === "boolean") { + data[cursor++] = (majorSpecial << 5) | (input ? specialTrue : specialFalse); + continue; + } + else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } + else if (Array.isArray(input)) { + for (let i = input.length - 1; i >= 0; --i) { + encodeStack.push(input[i]); + } + encodeHeader(majorList, input.length); + continue; + } + else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2); + encodeHeader(majorUnstructuredByteString, input.length); + data.set(input, cursor); + cursor += input.byteLength; + continue; + } + else if (typeof input === "object") { + if (input instanceof serde.NumericValue) { + const decimalIndex = input.string.indexOf("."); + const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; + const mantissa = BigInt(input.string.replace(".", "")); + data[cursor++] = 0b110_00100; + encodeStack.push(mantissa); + encodeStack.push(exponent); + encodeHeader(majorList, 2); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader(majorTag, input.tag); + continue; + } + else { + throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); + } + } + const keys = Object.keys(input); + for (let i = keys.length - 1; i >= 0; --i) { + const key = keys[i]; + encodeStack.push(input[key]); + encodeStack.push(key); + } + encodeHeader(majorMap, keys.length); + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); } - return false; - } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() +} + +const cbor = { + deserialize(payload) { + setPayload(payload); + return decode(0, payload.length); + }, + serialize(input) { + try { + encode(input); + return toUint8Array(); + } + catch (e) { + toUint8Array(); + throw e; + } + }, + resizeEncodingBuffer(size) { + resize(size); + }, +}; + +const parseCborBody = (streamBody, context) => { + return protocols.collectBody(streamBody, context).then(async (bytes) => { + if (bytes.length) { + try { + return cbor.deserialize(bytes); + } + catch (e) { + Object.defineProperty(e, "$responseBodyText", { + value: context.utf8Encoder(bytes), + }); + throw e; + } + } + return {}; }); - } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); - } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); - } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); +}; +const dateToTag = (date) => { + return tag({ + tag: 1, + value: date.getTime() / 1000, + }); +}; +const parseCborErrorBody = async (errorBody, context) => { + const value = await parseCborBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadSmithyRpcV2CborErrorCode = (output, data) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + const codeKey = Object.keys(data).find((key) => key.toLowerCase() === "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); } - const schema = this.getSchema(); - if (typeof schema === "number") { - return this.memberFrom([63 & schema, 0], "key"); +}; +const checkCborResponse = (response) => { + if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { + throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); } - return this.memberFrom([schema.keySchema, 0], "key"); - } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return this.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([63 & schema, 0], "member"); - } +}; +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers: { + ...headers, + }, + }; + if (resolvedHostname !== undefined) { + contents.hostname = resolvedHostname; } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); - } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return this.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([collection.valueSchema, 0], "member"); + if (body !== undefined) { + contents.body = body; + try { + contents.headers["content-length"] = String(utilBodyLengthBrowser.calculateBodyLength(body)); } - } + catch (e) { } } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); + return new protocolHttp.HttpRequest(contents); +}; + +class CborCodec extends protocols.SerdeContext { + createSerializer() { + const serializer = new CborShapeSerializer(); + serializer.setSerdeContext(this.serdeContext); + return serializer; } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); - } - /** - * @param member - to query. - * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). - */ - hasMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - return struct2.memberNames.includes(member); + createDeserializer() { + const deserializer = new CborShapeDeserializer(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; } - return false; - } - /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. - */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!struct2.memberNames.includes(member)) { - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); - } - const i = struct2.memberNames.indexOf(member); - const memberSchema = struct2.memberList[i]; - return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); +} +class CborShapeSerializer extends protocols.SerdeContext { + value; + write(schema, value) { + this.value = this.serialize(schema, value); } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + serialize(schema$1, source) { + const ns = schema.NormalizedSchema.of(schema$1); + if (source == null) { + if (ns.isIdempotencyToken()) { + return serde.generateIdempotencyToken(); + } + return source; + } + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(source); + } + return source; + } + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date((Number(source) / 1000) | 0)); + } + return dateToTag(source); + } + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i++] = value; + } + } + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key of Object.keys(sourceObject)) { + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + } + else if (ns.isDocumentSchema()) { + for (const key of Object.keys(sourceObject)) { + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + } + } + return newObject; + } + return source; } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); - } - /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @deprecated use (checked) structIterator instead. - * - * @returns a map of member names to member schemas (normalized). - */ - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; - } - } catch (ignored) { + flush() { + const buffer = cbor.serialize(this.value); + this.value = undefined; + return buffer; } - return buffer; - } - /** - * @returns member name of event stream or empty string indicating none exists or this - * isn't a structure schema. - */ - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; +} +class CborShapeDeserializer extends protocols.SerdeContext { + read(schema, bytes) { + const data = cbor.deserialize(bytes); + return this.readValue(schema, data); + } + readValue(_schema, value) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isTimestampSchema() && typeof value === "number") { + return serde._parseEpochTimestamp(value); + } + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + else if (typeof value === "function" || typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + if (itemValue != null || sparse) { + newArray.push(itemValue); + } + } + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const targetSchema = ns.getValueSchema(); + for (const key of Object.keys(value)) { + const itemValue = this.readValue(targetSchema, value[key]); + if (itemValue != null || sparse) { + newObject[key] = itemValue; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + newObject[key] = this.readValue(memberSchema, value[key]); + } + } + return newObject; + } + else { + return value; } - } } - return ""; - } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; +} + +class SmithyRpcV2CborProtocol extends protocols.RpcProtocol { + codec = new CborCodec(); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace }) { + super({ defaultNamespace }); } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; + getPayloadCodec() { + return this.codec; } - } - /** - * Creates a normalized member schema from the given schema and member name. - */ - memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType(), + }); + if (schema.deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } + else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + try { + request.headers["content-length"] = String(request.body.byteLength); + } + catch (e) { } + } + const { service, operation } = utilMiddleware.getSmithyContext(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } + else { + request.path += path; + } + return request; } - return new _NormalizedSchema(memberSchema, memberName); - } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); } - return "Unknown"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 24054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/serde/index.ts -var index_exports = {}; -__export(index_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort -}); -module.exports = __toCommonJS(index_exports); + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $response: response, + $fault: response.statusCode <= 500 ? "client" : "server", + }; + const registry = schema.TypeRegistry.for(namespace); + let errorSchema; + try { + errorSchema = registry.getSchema(errorName); + } + catch (e) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema); + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = schema.NormalizedSchema.of(errorSchema); + const ErrorCtor = registry.getErrorCtor(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/cbor"; + } +} -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; +exports.CborCodec = CborCodec; +exports.CborShapeDeserializer = CborShapeDeserializer; +exports.CborShapeSerializer = CborShapeSerializer; +exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol; +exports.buildHttpRpcRequest = buildHttpRpcRequest; +exports.cbor = cbor; +exports.checkCborResponse = checkCborResponse; +exports.dateToTag = dateToTag; +exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; +exports.parseCborBody = parseCborBody; +exports.parseCborErrorBody = parseCborErrorBody; +exports.tag = tag; +exports.tagSymbol = tagSymbol; -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } + +/***/ }), + +/***/ 86752: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilStream = __nccwpck_require__(71914); +var schema = __nccwpck_require__(41320); +var serde = __nccwpck_require__(98520); +var protocolHttp = __nccwpck_require__(13494); +var utilBase64 = __nccwpck_require__(82763); +var utilUtf8 = __nccwpck_require__(85339); + +const collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return utilStream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return utilStream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return utilStream.Uint8ArrayBlobAdapter.mutate(await fromContext); }; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +class SerdeContext { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } - if (value === 0) { - return false; +} + +class HttpProtocol extends SerdeContext { + options; + constructor(options) { + super(); + this.options = options; } - if (value === 1) { - return true; + getRequestType() { + return protocolHttp.HttpRequest; } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + getResponseType() { + return protocolHttp.HttpResponse; } - if (lower === "false") { - return false; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } } - if (lower === "true") { - return true; + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + if (!request.query) { + request.query = {}; + } + for (const [k, v] of endpoint.url.searchParams.entries()) { + request.query[k] = v; + } + return request; + } + else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : undefined; + request.path = endpoint.path; + request.query = { + ...endpoint.query, + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const operationNs = schema.NormalizedSchema.of(operationSchema); + const inputNs = schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], + }; } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest, + }); } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer, + }); + } + async loadEventStreamCapability() { + const { EventStreamSerde } = await __nccwpck_require__.e(/* import() */ 505).then(__nccwpck_require__.t.bind(__nccwpck_require__, 97505, 19)); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType(), + }); + } + getDefaultContentType() { + throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -var parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}; -var logger = { - warn: console.warn -}; - -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; } -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}; -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); -}; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; -}; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); - } - return input; -}; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; -}; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; - } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); - } -}; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; - } - return strictParseFloat32("0." + value) * 1e3; -}; -var parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); -}; -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(12048); +class HttpBindingProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ...(_input ?? {}), + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = schema.NormalizedSchema.of(operationSchema?.input); + const schema$1 = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new protocolHttp.HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = schema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } + else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns, + }); + } + } + else { + payload = inputMemberValue; + } + } + else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } + else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); + } + else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } + else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } + else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } + else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } + else { + hasNonHttpBindingMember = true; + } + } + if (hasNonHttpBindingMember && input) { + serializer.write(schema$1, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + ...traits, + httpQuery: key, + httpQueryParams: undefined, + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== undefined) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } + else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema$1, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } + else { + dataObject = arg4; + } + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(schema$1); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns, + }); + } + else { + dataObject[memberName] = utilStream.sdkStreamMixin(response.body); + } + } + else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } + else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && + headerListValueSchema.getSchema() === 4) { + sections = serde.splitEvery(value, ",", 2); + } + else { + sections = serde.splitHeader(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } + else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } + else if (memberTraits.httpPrefixHeaders !== undefined) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); + } + } + } + else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } + else { + nonHttpBindingMembers.push(memberName); + } + } + return nonHttpBindingMembers; + } +} + +class RpcProtocol extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = schema.NormalizedSchema.of(operationSchema?.input); + const schema$1 = ns.getSchema(); + let payload; + const request = new protocolHttp.HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "/", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input, + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest, + }); + } + } + else { + serializer.write(schema$1, _input); + payload = serializer.flush(); + } + } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = schema.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject, + }); + } + else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } +} -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); +const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== undefined) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel + ? labelValue + .split("/") + .map((segment) => extendedEncodeURIComponent(segment)) + .join("/") + : extendedEncodeURIComponent(labelValue)); } - }); - return str; -}; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); - } - return LazyJsonString(JSON.stringify(object)); + else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath; }; -LazyJsonString.fromObject = LazyJsonString.from; - -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} -// src/submodules/serde/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +class RequestBuilder { + input; + context; + query = {}; + method = ""; + headers = {}; + path = ""; + body = null; + hostname = ""; + resolvePathStack = []; + constructor(input, context) { + this.input = input; + this.context = context; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new protocolHttp.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers, + }); } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; + hn(hostname) { + this.hostname = hostname; + return this; + } + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + h(headers) { + this.headers = headers; + return this; + } + q(query) { + this.query = query; + return this; + } + b(body) { + this.body = body; + return this; + } + m(method) { + this.method = method; + return this; } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; } -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && + (ns.getSchema() === 5 || + ns.getSchema() === 6 || + ns.getSchema() === 7)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings + ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) + ? 6 + : Boolean(httpQuery) || Boolean(httpLabel) + ? 5 + : undefined + : undefined; + return bindingFormat ?? settings.timestampFormat.default; +} + +class FromStringShapeDeserializer extends SerdeContext { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + read(_schema, data) { + const ns = schema.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return serde.splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(data); } - break; - default: + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return serde._parseRfc3339DateTimeWithOffset(data); + case 6: + return serde._parseRfc7231DateTime(data); + case 7: + return serde._parseEpochTimestamp(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = serde.LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + if (ns.isNumericSchema()) { + return Number(data); + } + if (ns.isBigIntegerSchema()) { + return BigInt(data); + } + if (ns.isBigDecimalSchema()) { + return new serde.NumericValue(data, "bigDecimal"); + } + if (ns.isBooleanSchema()) { + return String(data).toLowerCase() === "true"; + } + return data; } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)((this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(base64String)); } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); +} + +class HttpInterceptingShapeDeserializer extends SerdeContext { + codecDeserializer; + stringDeserializer; + constructor(codecDeserializer, codecSettings) { + super(); + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema$1, data) { + const ns = schema.NormalizedSchema.of(schema$1); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } + else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } + } + return this.codecDeserializer.read(ns, data); } - return v.replace(/\\"/g, '"'); - }); -}; +} -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); +class ToStringShapeSerializer extends SerdeContext { + settings; + stringBuffer = ""; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + this.stringBuffer = serde.dateToUtcString(value); + break; + case 7: + this.stringBuffer = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1000); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : serde.quoteHeader(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = serde.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); } - dot = 1; - continue; - } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); - } } - } - toString() { - return this.string; - } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); - if (prototypeMatch) { - return prototypeMatch; +} + +class HttpInterceptingShapeSerializer { + codecSerializer; + stringSerializer; + buffer; + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { - return true; + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema$1, value) { + const ns = schema.NormalizedSchema.of(schema$1); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== undefined) { + const buffer = this.buffer; + this.buffer = undefined; + return buffer; + } + return this.codecSerializer.flush(); } - return prototypeMatch; - } -}; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); } -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.FromStringShapeDeserializer = FromStringShapeDeserializer; +exports.HttpBindingProtocol = HttpBindingProtocol; +exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer; +exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer; +exports.HttpProtocol = HttpProtocol; +exports.RequestBuilder = RequestBuilder; +exports.RpcProtocol = RpcProtocol; +exports.SerdeContext = SerdeContext; +exports.ToStringShapeSerializer = ToStringShapeSerializer; +exports.collectBody = collectBody; +exports.determineTimestampFormat = determineTimestampFormat; +exports.extendedEncodeURIComponent = extendedEncodeURIComponent; +exports.requestBuilder = requestBuilder; +exports.resolvedPath = resolvedPath; -/***/ }), -/***/ 90793: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +/***/ 41320: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/index.ts -var index_exports = {}; -__export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(index_exports); +"use strict"; -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(46572); -var import_querystring_builder = __nccwpck_require__(36600); -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); +var protocolHttp = __nccwpck_require__(13494); +var utilMiddleware = __nccwpck_require__(30954); -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); +const deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 + return schemaRef; }; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); + +class TypeRegistry { + namespace; + schemas; + exceptions; + static registries = new Map(); + constructor(namespace, schemas = new Map(), exceptions = new Map()) { + this.namespace = namespace; + this.schemas = schemas; + this.exceptions = exceptions; } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; + static for(namespace) { + if (!TypeRegistry.registries.has(namespace)) { + TypeRegistry.registries.set(namespace, new TypeRegistry(namespace)); + } + return TypeRegistry.registries.get(namespace); } - if (request.fragment) { - path += `#${request.fragment}`; + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + this.schemas.set(qualifiedName, schema); } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; + registerError(es, ctor) { + this.exceptions.set(es, ctor); } - if (body) { - requestOptions.duplex = "half"; + getErrorCtor(es) { + return this.exceptions.get(es); } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } + } + return undefined; } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; + find(predicate) { + return [...this.schemas.values()].find(predicate); } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); + clear() { + this.schemas.clear(); + this.exceptions.clear(); } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); + return this.namespace + "#" + shapeId; } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(76249); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); } -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + +class Schema { + name; + namespace; + traits; + static assign(instance, values) { + const schema = Object.assign(instance, values); + TypeRegistry.for(schema.namespace).register(schema.name, schema); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list = lhs; + return list.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; } -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); + +class StructureSchema extends Schema { + static symbol = Symbol.for("@smithy/str"); + name; + traits; + memberNames; + memberList; + symbol = StructureSchema.symbol; } -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: +const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList, +}); -0 && (0); +class ErrorSchema extends StructureSchema { + static symbol = Symbol.for("@smithy/err"); + ctor; + symbol = ErrorSchema.symbol; +} +const error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor: null, +}); + +class ListSchema extends Schema { + static symbol = Symbol.for("@smithy/lis"); + name; + traits; + valueSchema; + symbol = ListSchema.symbol; +} +const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema, +}); +class MapSchema extends Schema { + static symbol = Symbol.for("@smithy/map"); + name; + traits; + keySchema; + valueSchema; + symbol = MapSchema.symbol; +} +const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema, +}); +class OperationSchema extends Schema { + static symbol = Symbol.for("@smithy/ope"); + name; + traits; + input; + output; + symbol = OperationSchema.symbol; +} +const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output, +}); -/***/ }), +class SimpleSchema extends Schema { + static symbol = Symbol.for("@smithy/sim"); + name; + schemaRef; + traits; + symbol = SimpleSchema.symbol; +} +const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); -/***/ 56186: -/***/ ((module) => { +function translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams", + ]) { + if (((indicator >> i++) & 1) === 1) { + traits[trait] = 1; + } + } + return traits; +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +class NormalizedSchema { + ref; + memberName; + static symbol = Symbol.for("@smithy/nor"); + symbol = NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (isMemberSchema(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (isStaticSchema(schema)) + schema = hydrate(schema); + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, translateTraits(traitSet)); + } + } + else { + this.memberTraits = 0; + } + if (schema instanceof NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema); + this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } + else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? String(schema); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); + } + static of(ref) { + const sc = deref(ref); + if (sc instanceof NormalizedSchema) { + return sc; + } + if (isMemberSchema(sc)) { + const [ns, traits] = sc; + if (ns instanceof NormalizedSchema) { + Object.assign(ns.getMergedTraits(), translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + return new NormalizedSchema(sc); + } + getSchema() { + return deref(this.schema?.schemaRef ?? this.schema); + } + getName(withNamespace = false) { + const { name } = this; + const short = !withNamespace && name && name.includes("#"); + return short ? name.split("#")[1] : name || undefined; + } + getMemberName() { + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isListSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 64 && sc < 128 + : sc instanceof ListSchema; + } + isMapSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 128 && sc <= 0b1111_1111 + : sc instanceof MapSchema; + } + isStructSchema() { + const sc = this.getSchema(); + return (sc !== null && typeof sc === "object" && "members" in sc) || sc instanceof StructureSchema; + } + isBlobSchema() { + const sc = this.getSchema(); + return sc === 21 || sc === 42; + } + isTimestampSchema() { + const sc = this.getSchema(); + return (typeof sc === "number" && + sc >= 4 && + sc <= 7); + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isDocumentSchema() { + return this.getSchema() === 15; + } + isStringSchema() { + return this.getSchema() === 0; + } + isBooleanSchema() { + return this.getSchema() === 2; + } + isNumericSchema() { + return this.getSchema() === 1; + } + isBigIntegerSchema() { + return this.getSchema() === 17; + } + isBigDecimalSchema() { + return this.getSchema() === 19; + } + isStreaming() { + const { streaming } = this.getMergedTraits(); + return !!streaming || this.getSchema() === 42; + } + isIdempotencyToken() { + const match = (traits) => (traits & 0b0100) === 0b0100 || + !!traits?.idempotencyToken; + const { normalizedTraits, traits, memberTraits } = this; + return match(normalizedTraits) || match(traits) || match(memberTraits); + } + getMergedTraits() { + return (this.normalizedTraits ?? + (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits(), + })); + } + getMemberTraits() { + return translateTraits(this.memberTraits); + } + getOwnTraits() { + return translateTraits(this.traits); + } + getKeySchema() { + const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; + if (!isDoc && !isMap) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + const memberSchema = isDoc + ? 15 + : schema?.keySchema ?? 0; + return member([memberSchema, 0], "key"); + } + getValueSchema() { + const sc = this.getSchema(); + const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; + const memberSchema = typeof sc === "number" + ? 0b0011_1111 & sc + : sc && typeof sc === "object" && (isMap || isList) + ? sc.valueSchema + : isDoc + ? 15 + : void 0; + if (memberSchema != null) { + return member([memberSchema, 0], isMap ? "value" : "member"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + getMemberSchema(memberName) { + const struct = this.getSchema(); + if (this.isStructSchema() && struct.memberNames.includes(memberName)) { + const i = struct.memberNames.indexOf(memberName); + const memberSchema = struct.memberList[i]; + return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); + } + if (this.isDocumentSchema()) { + return member([15, 0], memberName); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no no member=${memberName}.`); + } + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } + catch (ignored) { } + return buffer; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct = this.getSchema(); + for (let i = 0; i < struct.memberNames.length; ++i) { + yield [struct.memberNames[i], member([struct.memberList[i], 0], struct.memberNames[i])]; + } + } +} +function member(memberSchema, memberName) { + if (memberSchema instanceof NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true, + }); + } + const internalCtorAccess = NormalizedSchema; + return new internalCtorAccess(memberSchema, memberName); +} +function hydrate(ss) { + const [id, ...rest] = ss; + return { + [0]: sim, + [1]: list, + [2]: map, + [3]: struct, + [-3]: error, + [9]: op, + }[id].call(null, ...rest); +} +const isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; +const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; + +const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + let { operationSchema } = utilMiddleware.getSmithyContext(context); + if (isStaticSchema(operationSchema)) { + operationSchema = hydrate(operationSchema); + } + try { + const parsed = await config.protocol.deserializeResponse(operationSchema, { + ...config, + ...context, + }, response); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (protocolHttp.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (e) { + } + } + throw error; + } }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: +const schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + let { operationSchema } = utilMiddleware.getSmithyContext(context); + if (isStaticSchema(operationSchema)) { + operationSchema = hydrate(operationSchema); + } + const endpoint = context.endpointV2?.url && config.urlParser + ? async () => config.urlParser(context.endpointV2.url) + : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint, + }); + return next({ + ...args, + request, + }); +}; -0 && (0); +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + }, + }; +} +const SCHEMA = { + BLOB: 0b0001_0101, + STREAMING_BLOB: 0b0010_1010, + BOOLEAN: 0b0000_0010, + STRING: 0b0000_0000, + NUMERIC: 0b0000_0001, + BIG_INTEGER: 0b0001_0001, + BIG_DECIMAL: 0b0001_0011, + DOCUMENT: 0b0000_1111, + TIMESTAMP_DEFAULT: 0b0000_0100, + TIMESTAMP_DATE_TIME: 0b0000_0101, + TIMESTAMP_HTTP_DATE: 0b0000_0110, + TIMESTAMP_EPOCH_SECONDS: 0b0000_0111, + LIST_MODIFIER: 0b0100_0000, + MAP_MODIFIER: 0b1000_0000, +}; + +exports.ErrorSchema = ErrorSchema; +exports.ListSchema = ListSchema; +exports.MapSchema = MapSchema; +exports.NormalizedSchema = NormalizedSchema; +exports.OperationSchema = OperationSchema; +exports.SCHEMA = SCHEMA; +exports.Schema = Schema; +exports.SimpleSchema = SimpleSchema; +exports.StructureSchema = StructureSchema; +exports.TypeRegistry = TypeRegistry; +exports.deref = deref; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.error = error; +exports.getSchemaSerdePlugin = getSchemaSerdePlugin; +exports.hydrate = hydrate; +exports.isStaticSchema = isStaticSchema; +exports.list = list; +exports.map = map; +exports.op = op; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.sim = sim; +exports.struct = struct; +exports.translateTraits = translateTraits; /***/ }), -/***/ 57217: +/***/ 98520: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointFromConfig = void 0; -const node_config_provider_1 = __nccwpck_require__(50240); -const getEndpointUrlConfig_1 = __nccwpck_require__(6416); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; - -/***/ }), - -/***/ 6416: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var uuid = __nccwpck_require__(90266); -"use strict"; +const copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = __nccwpck_require__(56700); -const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; -const CONFIG_ENDPOINT_URL = "endpoint_url"; -const getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env) => { - const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); - const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; +const parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}; +const expectBoolean = (value) => { + if (value === null || value === undefined) { return undefined; - }, - configFileSelector: (profile, config) => { - if (config && profile.services) { - const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); - const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl) - return endpointUrl; - } + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +const expectNumber = (value) => { + if (value === null || value === undefined) { return undefined; - }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; - - -/***/ }), - -/***/ 88075: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +const expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - endpointMiddleware: () => endpointMiddleware, - endpointMiddlewareOptions: () => endpointMiddlewareOptions, - getEndpointFromInstructions: () => getEndpointFromInstructions, - getEndpointPlugin: () => getEndpointPlugin, - resolveEndpointConfig: () => resolveEndpointConfig, - resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, - resolveParams: () => resolveParams, - toEndpointV1: () => toEndpointV1 -}); -module.exports = __toCommonJS(index_exports); - -// src/service-customizations/s3.ts -var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); +const expectLong = (value) => { + if (value === null || value === undefined) { + return undefined; } - } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { - endpointParams.ForcePathStyle = true; - } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; - } - return endpointParams; -}, "resolveParamsForS3"); -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); - } - return isValidArn; -}, "isArnBucketName"); - -// src/adaptors/createConfigValueProvider.ts -var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { - const configProvider = /* @__PURE__ */ __name(async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; } - return configValue; - }, "configProvider"); - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config.isCustomEndpoint === false) { - return void 0; - } - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname, port, path } = endpoint; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +const expectInt = expectLong; +const expectInt32 = (value) => expectSizedInt(value, 32); +const expectShort = (value) => expectSizedInt(value, 16); +const expectByte = (value) => expectSizedInt(value, 8); +const expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== undefined && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +const castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +const expectNonNull = (value, location) => { + if (value === null || value === undefined) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); } - } - return endpoint; - }; - } - return configProvider; -}, "createConfigValueProvider"); + throw new TypeError("Expected a non-null value"); + } + return value; +}; +const expectObject = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +const expectString = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +const expectUnion = (value) => { + if (value === null || value === undefined) { + return undefined; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject) + .filter(([, v]) => v != null) + .map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +const strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +const strictParseFloat = strictParseDouble; +const strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +const parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +const limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +const handleFloat = limitedParseDouble; +const limitedParseFloat = limitedParseDouble; +const limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +const parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +const strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +const strictParseInt = strictParseLong; +const strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +const strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +const strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +const stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message) + .split("\n") + .slice(0, 5) + .filter((s) => !s.includes("stackTraceWarning")) + .join("\n"); +}; +const logger = { + warn: console.warn, +}; -// src/adaptors/getEndpointFromInstructions.ts -var import_getEndpointFromConfig = __nccwpck_require__(57217); +const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +const parseRfc3339DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +const RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); +const parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET$1.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +const IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); +const parseRfc7231DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + match = RFC_850_DATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds, + })); + } + match = ASC_TIME$1.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +const parseEpochTimestamp = (value) => { + if (value === null || value === undefined) { + return undefined; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } + else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } + else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } + else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1000)); +}; +const buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); +}; +const parseTwoDigitYear = (value) => { + const thisYear = new Date().getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; +const adjustRfc850Year = (input) => { + if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); + } + return input; +}; +const parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +const isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +const parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +const parseMilliseconds = (value) => { + if (value === null || value === undefined) { + return 0; + } + return strictParseFloat32("0." + value) * 1000; +}; +const parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } + else if (directionStr == "-") { + direction = -1; + } + else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1000; +}; +const stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; -// src/adaptors/toEndpointV1.ts -var import_url_parser = __nccwpck_require__(38006); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return (0, import_url_parser.parseUrl)(endpoint.url); +const LazyJsonString = function LazyJsonString(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + }, + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; } - return endpoint; - } - return (0, import_url_parser.parseUrl)(endpoint); -}, "toEndpointV1"); + else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; -// src/adaptors/getEndpointFromInstructions.ts -var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); - } else { - endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} + +const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; +const mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; +const time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; +const date = `(\\d?\\d)`; +const year = `(\\d{4})`; +const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); +const IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`); +const RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`); +const ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`); +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const _parseEpochTimestamp = (value) => { + if (value == null) { + return void 0; + } + let num = NaN; + if (typeof value === "number") { + num = value; + } + else if (typeof value === "string") { + if (!/^-?\d*\.?\d+$/.test(value)) { + throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); + } + num = Number.parseFloat(value); } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; + else if (typeof value === "object" && value.tag === 1) { + num = value.value; } - } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); - } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}, "getEndpointFromInstructions"); -var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); - break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); - break; - default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + if (isNaN(num) || Math.abs(num) === Infinity) { + throw new TypeError("Epoch timestamps must be valid finite numbers."); } - } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; -}, "resolveParams"); + return new Date(Math.round(num * 1000)); +}; +const _parseRfc3339DateTimeWithOffset = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC3339 timestamps must be strings"); + } + const matches = RFC3339_WITH_OFFSET.exec(value); + if (!matches) { + throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); + } + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + range(monthStr, 1, 12); + range(dayStr, 1, 31); + range(hours, 0, 23); + range(minutes, 0, 59); + range(seconds, 0, 60); + const date = new Date(); + date.setUTCFullYear(Number(yearStr), Number(monthStr) - 1, Number(dayStr)); + date.setUTCHours(Number(hours)); + date.setUTCMinutes(Number(minutes)); + date.setUTCSeconds(Number(seconds)); + date.setUTCMilliseconds(Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0); + if (offsetStr.toUpperCase() != "Z") { + const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; + const scalar = sign === "-" ? 1 : -1; + date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); + } + return date; +}; +const _parseRfc7231DateTime = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC7231 timestamps must be strings."); + } + let day; + let month; + let year; + let hour; + let minute; + let second; + let fraction; + let matches; + if ((matches = IMF_FIXDATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + } + else if ((matches = RFC_850_DATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + year = (Number(year) + 1900).toString(); + } + else if ((matches = ASC_TIME.exec(value))) { + [, month, day, hour, minute, second, fraction, year] = matches; + } + if (year && second) { + const date = new Date(); + date.setUTCFullYear(Number(year)); + date.setUTCMonth(months.indexOf(month)); + range(day, 1, 31); + date.setUTCDate(Number(day)); + range(hour, 0, 23); + date.setUTCHours(Number(hour)); + range(minute, 0, 59); + date.setUTCMinutes(Number(minute)); + range(second, 0, 60); + date.setUTCSeconds(Number(second)); + date.setUTCMilliseconds(fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); + return date; + } + throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); +}; +function range(v, min, max) { + const _v = Number(v); + if (_v < min || _v > max) { + throw new Error(`Value ${_v} out of range [${min}, ${max}]`); + } +} -// src/endpointMiddleware.ts -var import_core = __nccwpck_require__(3402); -var import_util_middleware = __nccwpck_require__(26252); -var endpointMiddleware = /* @__PURE__ */ __name(({ - config, - instructions -}) => { - return (next, context) => async (args) => { - if (config.isCustomEndpoint) { - (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); } - const endpoint = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } + else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } - }, - { ...config }, - context - ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign( - httpAuthOption.signingProperties || {}, - { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet - }, - authScheme.properties - ); - } } - return next({ - ...args - }); - }; -}, "endpointMiddleware"); + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} -// src/getEndpointPlugin.ts -var import_middleware_serde = __nccwpck_require__(4783); -var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +const splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = undefined; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + } + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z = v.length; + if (z < 2) { + return v; + } + if (v[0] === `"` && v[z - 1] === `"`) { + v = v.slice(1, z - 1); + } + return v.replace(/\\"/g, '"'); + }); }; -var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - endpointMiddleware({ - config, - instructions - }), - endpointMiddlewareOptions - ); - }, "applyToStack") -}), "getEndpointPlugin"); - -// src/resolveEndpointConfig.ts -var import_getEndpointFromConfig2 = __nccwpck_require__(57217); -var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), - useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) - }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); +const format = /^-?\d*(\.\d+)?$/; +class NumericValue { + string; + type; + constructor(string, type) { + this.string = string; + this.type = type; + if (!format.test(string)) { + throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`); + } } - return configuredEndpointPromise; - }; - return resolvedConfig; -}, "resolveEndpointConfig"); + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === "bigDecimal" && format.test(_nv.string)); + } +} +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} -// src/resolveEndpointRequiredConfig.ts -var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - throw new Error( - "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." - ); - }; - } - return input; -}, "resolveEndpointRequiredConfig"); -// Annotate the CommonJS export names for ESM import in node: +Object.defineProperty(exports, "generateIdempotencyToken", ({ + enumerable: true, + get: function () { return uuid.v4; } +})); +exports.LazyJsonString = LazyJsonString; +exports.NumericValue = NumericValue; +exports._parseEpochTimestamp = _parseEpochTimestamp; +exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset; +exports._parseRfc7231DateTime = _parseRfc7231DateTime; +exports.copyDocumentWithTransform = copyDocumentWithTransform; +exports.dateToUtcString = dateToUtcString; +exports.expectBoolean = expectBoolean; +exports.expectByte = expectByte; +exports.expectFloat32 = expectFloat32; +exports.expectInt = expectInt; +exports.expectInt32 = expectInt32; +exports.expectLong = expectLong; +exports.expectNonNull = expectNonNull; +exports.expectNumber = expectNumber; +exports.expectObject = expectObject; +exports.expectShort = expectShort; +exports.expectString = expectString; +exports.expectUnion = expectUnion; +exports.handleFloat = handleFloat; +exports.limitedParseDouble = limitedParseDouble; +exports.limitedParseFloat = limitedParseFloat; +exports.limitedParseFloat32 = limitedParseFloat32; +exports.logger = logger; +exports.nv = nv; +exports.parseBoolean = parseBoolean; +exports.parseEpochTimestamp = parseEpochTimestamp; +exports.parseRfc3339DateTime = parseRfc3339DateTime; +exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; +exports.parseRfc7231DateTime = parseRfc7231DateTime; +exports.quoteHeader = quoteHeader; +exports.splitEvery = splitEvery; +exports.splitHeader = splitHeader; +exports.strictParseByte = strictParseByte; +exports.strictParseDouble = strictParseDouble; +exports.strictParseFloat = strictParseFloat; +exports.strictParseFloat32 = strictParseFloat32; +exports.strictParseInt = strictParseInt; +exports.strictParseInt32 = strictParseInt32; +exports.strictParseLong = strictParseLong; +exports.strictParseShort = strictParseShort; -0 && (0); +/***/ }), +/***/ 47299: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +"use strict"; -/***/ 4783: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var protocolHttp = __nccwpck_require__(13494); +var querystringBuilder = __nccwpck_require__(51346); +var utilBase64 = __nccwpck_require__(82763); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption -}); -module.exports = __toCommonJS(index_exports); +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} -// src/deserializerMiddleware.ts -var import_protocol_http = __nccwpck_require__(46572); -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); +} + +const keepAliveSupport = { + supported: undefined, +}; +class FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; + return new FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; + else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === undefined) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); } - } catch (e) { - } } - throw error; - } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); - -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = querystringBuilder.buildQueryString(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? undefined : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method: method, + credentials, + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { }; + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != undefined; + if (!hasReadableStream) { + return response.blob().then((body) => ({ + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body, + }), + })); + } + return { + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body, + }), + }; + }), + requestTimeout(requestTimeoutInMs), + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve, reject) => { + const onAbort = () => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true +const streamCollector = async (stream) => { + if ((typeof Blob === "function" && stream instanceof Blob) || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== undefined) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); }; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: /* @__PURE__ */ __name((commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, "applyToStack") - }; +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = utilBase64.fromBase64(base64); + return new Uint8Array(arrayBuffer); +} +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = (reader.result ?? ""); + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); } -__name(getSerdePlugin, "getSerdePlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +exports.FetchHttpHandler = FetchHttpHandler; +exports.keepAliveSupport = keepAliveSupport; +exports.streamCollector = streamCollector; /***/ }), -/***/ 50240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 67908: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(index_exports); -// src/configLoader.ts +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; +exports.isArrayBuffer = isArrayBuffer; -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(74558); -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } -} -__name(getSelectorName, "getSelectorName"); +/***/ }), -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); - } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); - } -}, "fromEnv"); +/***/ 8131: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/fromSharedConfigFiles.ts +"use strict"; -var import_shared_ini_file_loader = __nccwpck_require__(56700); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); - } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEndpointFromConfig = void 0; +const node_config_provider_1 = __nccwpck_require__(61814); +const getEndpointUrlConfig_1 = __nccwpck_require__(75974); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; -// src/fromStatic.ts -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +/***/ }), -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 75974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEndpointUrlConfig = void 0; +const shared_ini_file_loader_1 = __nccwpck_require__(93438); +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (config && profile.services) { + const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); +exports.getEndpointUrlConfig = getEndpointUrlConfig; /***/ }), -/***/ 60967: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(index_exports); - -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(46572); -var import_querystring_builder = __nccwpck_require__(36600); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); +/***/ 88205: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; +"use strict"; -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") -}; +var getEndpointFromConfig = __nccwpck_require__(8131); +var urlParser = __nccwpck_require__(85792); +var core = __nccwpck_require__(22744); +var utilMiddleware = __nccwpck_require__(30954); +var middlewareSerde = __nccwpck_require__(58305); -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); +const resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); + else if (!isDnsCompatibleBucketName(bucket) || + (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || + bucket.toLowerCase() !== bucket || + bucket.length < 3) { + endpointParams.ForcePathStyle = true; } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}; +const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +const DOTS_PATTERN = /\.\./; +const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); +const isArnBucketName = (bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}; -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; +const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { + const configProvider = async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} -__name(writeBody, "writeBody"); + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return undefined; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}; -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - static { - __name(this, "NodeHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; +const toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return urlParser.parseUrl(endpoint.url); + } + return endpoint; } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; + return urlParser.parseUrl(endpoint); +}; + +const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } + else { + endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + } } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; +}; +const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } - } } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}; + +const endpointMiddleware = ({ config, instructions, }) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + core.setFeature(context, "ENDPOINT_OVERRIDE", "N"); } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + }, + }, { ...config }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = utilMiddleware.getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet, + }, authScheme.properties); + } } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console + return next({ + ...args, + }); }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; +}; + +const endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: middlewareSerde.serializerMiddlewareOption.name, +}; +const getEndpointPlugin = (config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config, + instructions, + }), endpointMiddlewareOptions); + }, +}); + +const resolveEndpointConfig = (input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await utilMiddleware.normalizeProvider(endpoint)()) : undefined; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false), + }); + let configuredEndpointPromise = undefined; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; +}; + +const resolveEndpointRequiredConfig = (input) => { + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); + }; } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res + return input; +}; + +exports.endpointMiddleware = endpointMiddleware; +exports.endpointMiddlewareOptions = endpointMiddlewareOptions; +exports.getEndpointFromInstructions = getEndpointFromInstructions; +exports.getEndpointPlugin = getEndpointPlugin; +exports.resolveEndpointConfig = resolveEndpointConfig; +exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; +exports.resolveParams = resolveParams; +exports.toEndpointV1 = toEndpointV1; + + +/***/ }), + +/***/ 58305: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var protocolHttp = __nccwpck_require__(13494); + +const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (protocolHttp.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (e) { + } } - } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser + ? async () => endpointConfig.urlParser(context.endpointV2.url) + : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request, }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } }; -// src/node-http2-handler.ts +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, + }; +} + +exports.deserializerMiddleware = deserializerMiddleware; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.getSerdePlugin = getSerdePlugin; +exports.serializerMiddleware = serializerMiddleware; +exports.serializerMiddlewareOption = serializerMiddlewareOption; + +/***/ }), -var import_http22 = __nccwpck_require__(85675); +/***/ 61814: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); +"use strict"; -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - static { - __name(this, "NodeHttp2ConnectionPool"); - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); + +var propertyProvider = __nccwpck_require__(1104); +var sharedIniFileLoader = __nccwpck_require__(93438); + +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); + catch (e) { + return functionString; + } +} + +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); } - } + return config; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); } - } }; -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = sharedIniFileLoader.getProfileName(init); + const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; } - } - static { - __name(this, "NodeHttp2ConnectionManager"); - } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); +}; + +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); + +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +exports.loadConfig = loadConfig; + + +/***/ }), + +/***/ 95493: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var protocolHttp = __nccwpck_require__(13494); +var querystringBuilder = __nccwpck_require__(51346); +var http = __nccwpck_require__(58611); +var https = __nccwpck_require__(65692); +var stream = __nccwpck_require__(2203); +var http2 = __nccwpck_require__(85675); + +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +const getTransformedHeaders = (headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + return transformedHeaders; +}; + +const timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId), +}; + +const DEFER_EVENT_LISTENER_TIME$2 = 1000; +const setConnectionTimeout = (request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; + const registerTimeout = (offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { + name: "TimeoutError", + })); + }, timeoutInMs - offset); + const doWithSocket = (socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } + else { + timing.clearTimeout(timeoutId); + } + }; + if (request.socket) { + doWithSocket(request.socket); + } + else { + request.on("socket", doWithSocket); + } + }; + if (timeoutInMs < 2000) { + registerTimeout(0); + return 0; } - if (!existingConnectionPool.contains(session)) { - return; + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); +}; + +const setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => { + if (timeoutInMs) { + return timing.setTimeout(() => { + let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; + if (throwOnRequestTimeout) { + const error = Object.assign(new Error(msg), { + name: "TimeoutError", + code: "ETIMEDOUT", + }); + req.destroy(error); + reject(error); + } + else { + msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; + logger?.warn?.(msg); + } + }, timeoutInMs); } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); + return -1; +}; + +const DEFER_EVENT_LISTENER_TIME$1 = 3000; +const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = () => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); } - connectionPool.remove(session); - } - this.sessionCache.delete(key); + else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }; + if (deferTimeMs === 0) { + registerListener(); + return 0; } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + return timing.setTimeout(registerListener, deferTimeMs); +}; + +const DEFER_EVENT_LISTENER_TIME = 3000; +const setSocketTimeout = (request, reject, timeoutInMs = 0) => { + const registerTimeout = (offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = () => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); + }; + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } + else { + request.setTimeout(timeout, onTimeout); + } + }; + if (0 < timeoutInMs && timeoutInMs < 6000) { + registerTimeout(0); + return 0; } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } + return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); }; -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); - } - static { - __name(this, "NodeHttp2Handler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; +const MIN_WAIT_TIME = 6_000; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }), + ]); } - return new _NodeHttp2Handler(instanceOrOptions); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } + if (sendBody) { + writeBody(httpRequest, request.body); } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); +} +function writeBody(httpRequest, body) { + if (body instanceof stream.Readable) { + body.pipe(httpRequest); return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); + const uint8 = body; + if (typeof uint8 === "object" && + uint8.buffer && + typeof uint8.byteOffset === "number" && + typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} + +const DEFAULT_REQUEST_TIMEOUT = 0; +class NodeHttpHandler { + config; + configProvider; + socketWarningTimestamp = 0; + metadata = { handlerProtocol: "http/1.1" }; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttpHandler(instanceOrOptions); + } + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15_000; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }) + .catch(reject); + } + else { + resolve(this.resolveDefaultConfig(options)); + } }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout, + socketTimeout, + socketAcquisitionWarningTimeout, + throwOnRequestTimeout, + httpAgent: (() => { + if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console, + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = undefined; + const timeouts = []; + const resolve = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }; + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push(timing.setTimeout(() => { + this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger); + }, this.config.socketAcquisitionWarningTimeout ?? + (this.config.requestTimeout ?? 2000) + (this.config.connectionTimeout ?? 1000))); + const queryString = querystringBuilder.buildQueryString(request.query || {}); + let auth = undefined; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } + else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth, + }; + const requestFunc = isSSL ? https.request : http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res, + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } + else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = () => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, this.config.throwOnRequestTimeout, this.config.logger ?? console)); + timeouts.push(setSocketTimeout(req, reject, this.config.socketTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push(setSocketKeepAlive(req, { + keepAlive: httpAgent.keepAlive, + keepAliveMsecs: httpAgent.keepAliveMsecs, + })); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} + +class NodeHttp2ConnectionPool { + sessions = []; + constructor(sessions) { + this.sessions = sessions ?? []; + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } +} + +class NodeHttp2ConnectionManager { + constructor(config) { + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + config; + sessionCache = new Map(); + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = http2.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error("Fail to set maxConcurrentStreams to " + + this.config.maxConcurrency + + "when creating new session for " + + requestContext.destination.toString()); + } + }); } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { session.unref(); - if (disableConcurrentStreams) { - session.destroy(); + const destroySessionCb = () => { + session.destroy(); + this.deleteSession(url, session); + }; + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; + } + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + if (!existingConnectionPool.contains(session)) { + return; } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); } - } -}; - -// src/stream-collector/collector.ts + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +} -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } -}; +class NodeHttp2Handler { + config; + configProvider; + metadata = { handlerProtocol: "h2" }; + connectionManager = new NodeHttp2ConnectionManager({}); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttp2Handler(instanceOrOptions); + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((opts) => { + resolve(opts || {}); + }) + .catch(reject); + } + else { + resolve(options || {}); + } + }); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = undefined; + const resolve = async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }; + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false, + }); + const rejectWithDestroy = (err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }; + const queryString = querystringBuilder.buildQueryString(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [http2.constants.HTTP2_HEADER_PATH]: path, + [http2.constants.HTTP2_HEADER_METHOD]: method, + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req, + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = () => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } + } +} -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); +class Collector extends stream.Writable { + bufferedBytes = []; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +} + +const streamCollector = (stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +}; +const isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; } -__name(collectReadableStream, "collectReadableStream"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; +exports.NodeHttp2Handler = NodeHttp2Handler; +exports.NodeHttpHandler = NodeHttpHandler; +exports.streamCollector = streamCollector; /***/ }), -/***/ 74558: -/***/ ((module) => { +/***/ 1104: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +} -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); + } +} -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); + } +} -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - } - throw lastProviderError; -}, "chain"); + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +const fromStatic = (staticValue) => () => Promise.resolve(staticValue); -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +}; +exports.CredentialsProviderError = CredentialsProviderError; +exports.ProviderError = ProviderError; +exports.TokenProviderError = TokenProviderError; +exports.chain = chain; +exports.fromStatic = fromStatic; +exports.memoize = memoize; /***/ }), -/***/ 46572: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); +/***/ 13494: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/Field.ts -var import_types = __nccwpck_require__(42394); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; +"use strict"; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; -// src/httpRequest.ts +var types = __nccwpck_require__(50892); -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; - } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); - } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } }; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } } -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; /***/ }), -/***/ 36600: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51346: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; + + +var utilUriEscape = __nccwpck_require__(72644); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(54474); function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } } - } - return parts.join("&"); + return parts.join("&"); } -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +exports.buildQueryString = buildQueryString; /***/ }), -/***/ 83966: -/***/ ((module) => { +/***/ 18352: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseQueryString: () => parseQueryString -}); -module.exports = __toCommonJS(index_exports); function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; - } + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } + else if (Array.isArray(query[key])) { + query[key].push(value); + } + else { + query[key] = [query[key], value]; + } + } } - } - return query; + return query; } -__name(parseQueryString, "parseQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +exports.parseQueryString = parseQueryString; /***/ }), -/***/ 59652: +/***/ 91690: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44986,7 +31200,7 @@ exports.getHomeDir = getHomeDir; /***/ }), -/***/ 17621: +/***/ 66531: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44995,7 +31209,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFilepath = void 0; const crypto_1 = __nccwpck_require__(76982); const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(59652); +const getHomeDir_1 = __nccwpck_require__(91690); const getSSOTokenFilepath = (id) => { const hasher = (0, crypto_1.createHash)("sha1"); const cacheName = hasher.update(id).digest("hex"); @@ -45006,7 +31220,7 @@ exports.getSSOTokenFilepath = getSSOTokenFilepath; /***/ }), -/***/ 81910: +/***/ 83280: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45014,7 +31228,7 @@ exports.getSSOTokenFilepath = getSSOTokenFilepath; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(17621); +const getSSOTokenFilepath_1 = __nccwpck_require__(66531); const { readFile } = fs_1.promises; exports.tokenIntercept = {}; const getSSOTokenFromFile = async (id) => { @@ -45030,1549 +31244,2260 @@ exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 56700: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 93438: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + + +var getHomeDir = __nccwpck_require__(91690); +var getSSOTokenFilepath = __nccwpck_require__(66531); +var getSSOTokenFromFile = __nccwpck_require__(83280); +var path = __nccwpck_require__(16928); +var types = __nccwpck_require__(50892); +var slurpFile = __nccwpck_require__(95016); + +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; +}, { + ...(data.default && { default: data.default }), +}); + +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } + } + return map; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; + +const swallowError$1 = () => ({}); +const CONFIG_PREFIX_SEPARATOR = "."; +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir.getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = path.join(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + slurpFile.slurpFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + slurpFile.slurpFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => slurpFile.slurpFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); + +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } + } + } + return merged; +}; + +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; + +const externalDataInterceptor = { + getFileRecord() { + return slurpFile.fileIntercept; + }, + interceptFile(path, contents) { + slurpFile.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + getSSOTokenFromFile.tokenIntercept[id] = contents; + }, +}; + +Object.defineProperty(exports, "getSSOTokenFromFile", ({ + enumerable: true, + get: function () { return getSSOTokenFromFile.getSSOTokenFromFile; } +})); +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.ENV_PROFILE = ENV_PROFILE; +exports.externalDataInterceptor = externalDataInterceptor; +exports.getProfileName = getProfileName; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.parseKnownFiles = parseKnownFiles; +Object.keys(getHomeDir).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getHomeDir[k]; } + }); +}); +Object.keys(getSSOTokenFilepath).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getSSOTokenFilepath[k]; } + }); }); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(59652), module.exports); -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/index.ts -__reExport(index_exports, __nccwpck_require__(17621), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(81910); +/***/ }), + +/***/ 95016: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || options?.ignoreCache) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 50892: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; + + +/***/ }), + +/***/ 85792: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var querystringParser = __nccwpck_require__(18352); + +const parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = querystringParser.parseQueryString(search); + } + return { + hostname, + port: port ? parseInt(port) : undefined, + protocol, + path: pathname, + query, + }; +}; + +exports.parseUrl = parseUrl; + + +/***/ }), + +/***/ 1724: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(40037); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; + + +/***/ }), + +/***/ 82763: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var fromBase64 = __nccwpck_require__(1724); +var toBase64 = __nccwpck_require__(99617); + + + +Object.keys(fromBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return fromBase64[k]; } + }); +}); +Object.keys(toBase64).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return toBase64[k]; } + }); +}); + + +/***/ }), + +/***/ 99617: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(40037); +const util_utf8_1 = __nccwpck_require__(85339); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; + + +/***/ }), + +/***/ 84916: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; +const calculateBodyLength = (body) => { + if (typeof body === "string") { + if (TEXT_ENCODER) { + return TEXT_ENCODER.encode(body).byteLength; + } + let len = body.length; + for (let i = len - 1; i >= 0; i--) { + const code = body.charCodeAt(i); + if (code > 0x7f && code <= 0x7ff) + len++; + else if (code > 0x7ff && code <= 0xffff) + len += 2; + if (code >= 0xdc00 && code <= 0xdfff) + i--; + } + return len; + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + throw new Error(`Body Length computation failed for ${body}`); +}; + +exports.calculateBodyLength = calculateBodyLength; + + +/***/ }), + +/***/ 40037: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var isArrayBuffer = __nccwpck_require__(67908); +var buffer = __nccwpck_require__(20181); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; + + +/***/ }), + +/***/ 70397: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; + + +/***/ }), + +/***/ 30954: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(50892); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; + + +/***/ }), + +/***/ 96338: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + allocByteArray; + byteLength = 0; + byteArrays = []; + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; + -// src/loadSharedConfigFiles.ts +/***/ }), +/***/ 73787: +/***/ ((__unused_webpack_module, exports) => { -// src/getConfigData.ts -var import_types = __nccwpck_require__(42394); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); +"use strict"; -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(59652); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; -// src/getCredentialsFilepath.ts -var import_getHomeDir2 = __nccwpck_require__(59652); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); +/***/ }), -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(59652); +/***/ 13821: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/parseIni.ts +"use strict"; -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(82763); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + expectedChecksum; + checksumSourceLocation; + checksum; + source; + base64Encoder; + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + super(); + if (typeof source.pipe === "function") { + this.source = source; } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; + else { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); } - } + this.base64Encoder = base64Encoder ?? util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); } - } - return map; -}, "parseIni"); + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); + } + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); + } +} +exports.ChecksumStream = ChecksumStream; -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(89198); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); -// src/getSsoSessionData.ts +/***/ }), -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); +/***/ 17227: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(89198); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +"use strict"; -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(82763); +const stream_type_check_1 = __nccwpck_require__(68604); +const ChecksumStream_browser_1 = __nccwpck_require__(73787); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); } - } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); - -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(81910); -var import_slurpFile3 = __nccwpck_require__(89198); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } + const encoder = base64Encoder ?? util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; }; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.createChecksumStream = createChecksumStream; /***/ }), -/***/ 89198: +/***/ 5869: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(68604); +const ChecksumStream_1 = __nccwpck_require__(13821); +const createChecksumStream_browser_1 = __nccwpck_require__(17227); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; + return new ChecksumStream_1.ChecksumStream(init); +} /***/ }), -/***/ 42394: -/***/ ((module) => { +/***/ 77523: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(96338); +const createBufferedReadableStream_1 = __nccwpck_require__(55971); +const stream_type_check_1 = __nccwpck_require__(68604); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); + } + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +/***/ }), -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +/***/ 55971: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(96338); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + return chunk?.byteLength ?? chunk?.length ?? 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); + if (typeof chunk === "string") { + return 0; + } + return -1; +} -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +/***/ }), -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: +/***/ 25024: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +}; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; /***/ }), -/***/ 38006: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseUrl: () => parseUrl -}); -module.exports = __toCommonJS(index_exports); -var import_querystring_parser = __nccwpck_require__(83966); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 46916: +/***/ ((__unused_webpack_module, exports) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += value?.byteLength ?? 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} /***/ }), -/***/ 38330: +/***/ 66922: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(54351); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); - } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(46916); +const stream_type_check_1 = __nccwpck_require__(68604); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); }; -exports.fromBase64 = fromBase64; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + buffers = []; + limit = Infinity; + bytesBuffered = 0; + _write(chunk, encoding, callback) { + this.buffers.push(chunk); + this.bytesBuffered += chunk.byteLength ?? 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} /***/ }), -/***/ 76249: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 71914: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(38330), module.exports); -__reExport(index_exports, __nccwpck_require__(97055), module.exports); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +var utilBase64 = __nccwpck_require__(82763); +var utilUtf8 = __nccwpck_require__(85339); +var ChecksumStream = __nccwpck_require__(13821); +var createChecksumStream = __nccwpck_require__(5869); +var createBufferedReadable = __nccwpck_require__(77523); +var getAwsChunkedEncodingStream = __nccwpck_require__(25024); +var headStream = __nccwpck_require__(66922); +var sdkStreamMixin = __nccwpck_require__(51027); +var splitStream = __nccwpck_require__(39346); +var streamTypeCheck = __nccwpck_require__(68604); + +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return utilBase64.toBase64(payload); + } + return utilUtf8.toUtf8(payload); +} +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(str)); + } + return Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(str)); +} + +class Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + if (typeof source === "string") { + return transformFromString(source, encoding); + } + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + static mutate(source) { + Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } +} +exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; +Object.keys(ChecksumStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return ChecksumStream[k]; } + }); +}); +Object.keys(createChecksumStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return createChecksumStream[k]; } + }); +}); +Object.keys(createBufferedReadable).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return createBufferedReadable[k]; } + }); +}); +Object.keys(getAwsChunkedEncodingStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getAwsChunkedEncodingStream[k]; } + }); +}); +Object.keys(headStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return headStream[k]; } + }); +}); +Object.keys(sdkStreamMixin).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return sdkStreamMixin[k]; } + }); +}); +Object.keys(splitStream).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return splitStream[k]; } + }); +}); +Object.keys(streamTypeCheck).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return streamTypeCheck[k]; } + }); +}); /***/ }), -/***/ 97055: +/***/ 60445: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(54351); -const util_utf8_1 = __nccwpck_require__(55969); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } - else { - input = _input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(47299); +const util_base64_1 = __nccwpck_require__(82763); +const util_hex_encoding_1 = __nccwpck_require__(70397); +const util_utf8_1 = __nccwpck_require__(85339); +const stream_type_check_1 = __nccwpck_require__(68604); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 54351: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(56186); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; /***/ }), -/***/ 61307: -/***/ ((module) => { +/***/ 51027: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(95493); +const util_buffer_from_1 = __nccwpck_require__(40037); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(60445); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } + catch (e) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } } - } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; /***/ }), -/***/ 26252: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 70988: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(index_exports); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(42394); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: +/***/ }), -0 && (0); +/***/ 39346: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(70988); +const stream_type_check_1 = __nccwpck_require__(68604); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} /***/ }), -/***/ 47324: +/***/ 68604: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; - } -} -exports.ByteArrayCollector = ByteArrayCollector; +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => typeof ReadableStream === "function" && + (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; /***/ }), -/***/ 75233: +/***/ 72644: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; /***/ }), -/***/ 97975: +/***/ 85339: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(76249); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); + +var utilBufferFrom = __nccwpck_require__(40037); + +const fromUtf8 = (input) => { + const buf = utilBufferFrom.fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toUint8Array = (data) => { + if (typeof data === "string") { + return fromUtf8(data); } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); + return new Uint8Array(data); +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; } -} -exports.ChecksumStream = ChecksumStream; + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +exports.fromUtf8 = fromUtf8; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8; /***/ }), -/***/ 58473: +/***/ 62041: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(76249); -const stream_type_check_1 = __nccwpck_require__(17782); -const ChecksumStream_browser_1 = __nccwpck_require__(75233); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(8704); +const util_middleware_1 = __nccwpck_require__(26252); +const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region, }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccountRoles": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccounts": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "Logout": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; }; -exports.createChecksumStream = createChecksumStream; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; /***/ }), -/***/ 53535: +/***/ 13903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(17782); -const ChecksumStream_1 = __nccwpck_require__(97975); -const createChecksumStream_browser_1 = __nccwpck_require__(58473); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(83068); +const util_endpoints_2 = __nccwpck_require__(79674); +const ruleset_1 = __nccwpck_require__(41308); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; /***/ }), -/***/ 76861: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41308: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(47324); -const createBufferedReadableStream_1 = __nccwpck_require__(74381); -const stream_type_check_1 = __nccwpck_require__(17782); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; + + +/***/ }), + +/***/ 62054: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, + GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, + GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, + InvalidRequestException: () => InvalidRequestException, + ListAccountRolesCommand: () => ListAccountRolesCommand, + ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, + ListAccountsCommand: () => ListAccountsCommand, + ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, + LogoutCommand: () => LogoutCommand, + LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, + ResourceNotFoundException: () => ResourceNotFoundException, + RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, + SSO: () => SSO, + SSOClient: () => SSOClient, + SSOServiceException: () => SSOServiceException, + TooManyRequestsException: () => TooManyRequestsException, + UnauthorizedException: () => UnauthorizedException, + __Client: () => import_smithy_client.Client, + paginateListAccountRoles: () => paginateListAccountRoles, + paginateListAccounts: () => paginateListAccounts +}); +module.exports = __toCommonJS(index_exports); + +// src/SSOClient.ts +var import_middleware_host_header = __nccwpck_require__(52590); +var import_middleware_logger = __nccwpck_require__(85242); +var import_middleware_recursion_detection = __nccwpck_require__(81568); +var import_middleware_user_agent = __nccwpck_require__(32959); +var import_config_resolver = __nccwpck_require__(39316); +var import_core = __nccwpck_require__(3402); +var import_middleware_content_length = __nccwpck_require__(47212); +var import_middleware_endpoint = __nccwpck_require__(88075); +var import_middleware_retry = __nccwpck_require__(19618); + +var import_httpAuthSchemeProvider = __nccwpck_require__(62041); + +// src/endpoint/EndpointParameters.ts +var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal" + }); +}, "resolveClientEndpointParameters"); +var commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +}; + +// src/SSOClient.ts +var import_runtimeConfig = __nccwpck_require__(82696); + +// src/runtimeExtensions.ts +var import_region_config_resolver = __nccwpck_require__(36463); +var import_protocol_http = __nccwpck_require__(46572); +var import_smithy_client = __nccwpck_require__(61411); + +// src/auth/httpAuthExtensionConfiguration.ts +var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; -} + }; +}, "getHttpAuthExtensionConfiguration"); +var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}, "resolveHttpAuthRuntimeConfig"); + +// src/runtimeExtensions.ts +var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign( + (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), + (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), + (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), + getHttpAuthExtensionConfiguration(runtimeConfig) + ); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign( + runtimeConfig, + (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), + (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), + (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), + resolveHttpAuthRuntimeConfig(extensionConfiguration) + ); +}, "resolveRuntimeExtensions"); +// src/SSOClient.ts +var SSOClient = class extends import_smithy_client.Client { + static { + __name(this, "SSOClient"); + } + /** + * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. + */ + config; + constructor(...[configuration]) { + const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use( + (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }), "identityProviderConfigProvider") + }) + ); + this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); + } + /** + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. + */ + destroy() { + super.destroy(); + } +}; -/***/ }), +// src/SSO.ts -/***/ 74381: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// src/commands/GetRoleCredentialsCommand.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(47324); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; - } - return -1; -} +var import_middleware_serde = __nccwpck_require__(4783); -/***/ }), +// src/models/models_0.ts -/***/ 42098: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// src/models/SSOServiceException.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); +var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "SSOServiceException"); + } + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOServiceException.prototype); + } +}; + +// src/models/models_0.ts +var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { + static { + __name(this, "InvalidRequestException"); + } + name = "InvalidRequestException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + } +}; +var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { + static { + __name(this, "ResourceNotFoundException"); + } + name = "ResourceNotFoundException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts }); - return awsChunkedEncodingStream; + Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); + } }; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { + static { + __name(this, "TooManyRequestsException"); + } + name = "TooManyRequestsException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsException.prototype); + } +}; +var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { + static { + __name(this, "UnauthorizedException"); + } + name = "UnauthorizedException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedException.prototype); + } +}; +var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "GetRoleCredentialsRequestFilterSensitiveLog"); +var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, + ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } +}), "RoleCredentialsFilterSensitiveLog"); +var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } +}), "GetRoleCredentialsResponseFilterSensitiveLog"); +var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "ListAccountRolesRequestFilterSensitiveLog"); +var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "ListAccountsRequestFilterSensitiveLog"); +var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "LogoutRequestFilterSensitiveLog"); + +// src/protocols/Aws_restJson1.ts +var import_core2 = __nccwpck_require__(8704); -/***/ }), +var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/federation/credentials"); + const query = (0, import_smithy_client.map)({ + [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], + [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_GetRoleCredentialsCommand"); +var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/assignment/roles"); + const query = (0, import_smithy_client.map)({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], + [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_ListAccountRolesCommand"); +var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/assignment/accounts"); + const query = (0, import_smithy_client.map)({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_ListAccountsCommand"); +var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/logout"); + let body; + b.m("POST").h(headers).b(body); + return b.build(); +}, "se_LogoutCommand"); +var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + roleCredentials: import_smithy_client._json + }); + Object.assign(contents, doc); + return contents; +}, "de_GetRoleCredentialsCommand"); +var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + nextToken: import_smithy_client.expectString, + roleList: import_smithy_client._json + }); + Object.assign(contents, doc); + return contents; +}, "de_ListAccountRolesCommand"); +var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + accountList: import_smithy_client._json, + nextToken: import_smithy_client.expectString + }); + Object.assign(contents, doc); + return contents; +}, "de_ListAccountsCommand"); +var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); + } + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + await (0, import_smithy_client.collectBody)(output.body, context); + return contents; +}, "de_LogoutCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core2.parseJsonErrorBody)(output.body, context) + }; + const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); + switch (errorCode) { + case "InvalidRequestException": + case "com.amazonaws.sso#InvalidRequestException": + throw await de_InvalidRequestExceptionRes(parsedOutput, context); + case "ResourceNotFoundException": + case "com.amazonaws.sso#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); + case "TooManyRequestsException": + case "com.amazonaws.sso#TooManyRequestsException": + throw await de_TooManyRequestsExceptionRes(parsedOutput, context); + case "UnauthorizedException": + case "com.amazonaws.sso#UnauthorizedException": + throw await de_UnauthorizedExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode + }); + } +}, "de_CommandError"); +var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); +var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidRequestExceptionRes"); +var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_ResourceNotFoundExceptionRes"); +var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new TooManyRequestsException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_TooManyRequestsExceptionRes"); +var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new UnauthorizedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnauthorizedExceptionRes"); +var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] +}), "deserializeMetadata"); +var _aI = "accountId"; +var _aT = "accessToken"; +var _ai = "account_id"; +var _mR = "maxResults"; +var _mr = "max_result"; +var _nT = "nextToken"; +var _nt = "next_token"; +var _rN = "roleName"; +var _rn = "role_name"; +var _xasbt = "x-amz-sso_bearer_token"; + +// src/commands/GetRoleCredentialsCommand.ts +var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { + static { + __name(this, "GetRoleCredentialsCommand"); + } +}; -/***/ 39562: -/***/ ((__unused_webpack_module, exports) => { +// src/commands/ListAccountRolesCommand.ts -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; -} +var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { + static { + __name(this, "ListAccountRolesCommand"); + } +}; -/***/ }), +// src/commands/ListAccountsCommand.ts -/***/ 53188: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(39562); -const stream_type_check_1 = __nccwpck_require__(17782); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); +var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { + static { + __name(this, "ListAccountsCommand"); + } }; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; - } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } -} +// src/commands/LogoutCommand.ts -/***/ }), -/***/ 64356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { + static { + __name(this, "LogoutCommand"); } - return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter -}); -module.exports = __toCommonJS(index_exports); - -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(76249); -var import_util_utf8 = __nccwpck_require__(55969); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { +// src/SSO.ts +var commands = { + GetRoleCredentialsCommand, + ListAccountRolesCommand, + ListAccountsCommand, + LogoutCommand +}; +var SSO = class extends SSOClient { static { - __name(this, "Uint8ArrayBlobAdapter"); - } - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); + __name(this, "SSO"); } }; +(0, import_smithy_client.createAggregatedClient)(commands, SSO); -// src/index.ts -__reExport(index_exports, __nccwpck_require__(97975), module.exports); -__reExport(index_exports, __nccwpck_require__(53535), module.exports); -__reExport(index_exports, __nccwpck_require__(76861), module.exports); -__reExport(index_exports, __nccwpck_require__(42098), module.exports); -__reExport(index_exports, __nccwpck_require__(53188), module.exports); -__reExport(index_exports, __nccwpck_require__(23657), module.exports); -__reExport(index_exports, __nccwpck_require__(60964), module.exports); -__reExport(index_exports, __nccwpck_require__(17782), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +// src/pagination/ListAccountRolesPaginator.ts +var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); -/***/ }), +// src/pagination/ListAccountsPaginator.ts -/***/ 9655: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(90793); -const util_base64_1 = __nccwpck_require__(76249); -const util_hex_encoding_1 = __nccwpck_require__(61307); -const util_utf8_1 = __nccwpck_require__(55969); -const stream_type_check_1 = __nccwpck_require__(17782); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; /***/ }), -/***/ 23657: +/***/ 82696: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; +exports.getRuntimeConfig = void 0; +const tslib_1 = __nccwpck_require__(61860); +const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(45188)); +const core_1 = __nccwpck_require__(8704); +const util_user_agent_node_1 = __nccwpck_require__(51656); +const config_resolver_1 = __nccwpck_require__(39316); +const hash_node_1 = __nccwpck_require__(5092); +const middleware_retry_1 = __nccwpck_require__(19618); +const node_config_provider_1 = __nccwpck_require__(50240); const node_http_handler_1 = __nccwpck_require__(60967); -const util_buffer_from_1 = __nccwpck_require__(54351); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(9655); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); +const util_body_length_node_1 = __nccwpck_require__(13638); +const util_retry_1 = __nccwpck_require__(15518); +const runtimeConfig_shared_1 = __nccwpck_require__(8073); +const smithy_client_1 = __nccwpck_require__(61411); +const util_defaults_mode_node_1 = __nccwpck_require__(15435); +const smithy_client_2 = __nccwpck_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); }; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), - -/***/ 36874: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); -} +exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 60964: +/***/ 8073: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(36874); -const stream_type_check_1 = __nccwpck_require__(17782); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); - } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} - - -/***/ }), - -/***/ 17782: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; - - -/***/ }), - -/***/ 54474: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(8704); +const core_2 = __nccwpck_require__(3402); +const smithy_client_1 = __nccwpck_require__(61411); +const url_parser_1 = __nccwpck_require__(38006); +const util_base64_1 = __nccwpck_require__(76249); +const util_utf8_1 = __nccwpck_require__(55969); +const httpAuthSchemeProvider_1 = __nccwpck_require__(62041); +const endpointResolver_1 = __nccwpck_require__(13903); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 55969: +/***/ 3402: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -46597,165 +33522,425 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature }); module.exports = __toCommonJS(index_exports); -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(54351); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(42394); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(26252); + +// src/middleware-http-auth-scheme/resolveAuthOptions.ts +var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; +}, "resolveAuthOptions"); -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + return map; +} +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + ); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}, "httpAuthSchemeMiddleware"); +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" +}; +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); -/***/ }), +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(4783); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemePlugin"); -/***/ 8704: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(46572); -"use strict"; +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(61860); -tslib_1.__exportStar(__nccwpck_require__(5152), exports); -tslib_1.__exportStar(__nccwpck_require__(97523), exports); -tslib_1.__exportStar(__nccwpck_require__(37288), exports); +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" +}; +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + }, "applyToStack") +}), "getHttpSigningPlugin"); +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); -/***/ }), +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return void 0; + }, "paginateOperation"); +} +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; + } + cursor = cursor[step]; + } + return cursor; +}, "get"); -/***/ 5152: -/***/ ((module) => { +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(50678); -"use strict"; +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +__name(setFeature, "setFeature"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { + /** + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure + */ + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } + } + static { + __name(this, "DefaultIdentityProviderConfig"); + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/client/index.ts -var index_exports = {}; -__export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state -}); -module.exports = __toCommonJS(index_exports); +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false + +var HttpApiKeyAuthSigner = class { + static { + __name(this, "HttpApiKeyAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); + } + return clonedRequest; + } }; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts -More information can be found at: https://a.co/74kJMmI` - ); +var HttpBearerAuthSigner = class { + static { + __name(this, "HttpBearerAuthSigner"); } -}, "emitWarningIfUnsupportedVersion"); - -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; } - credentials.$source[feature] = value; - return credentials; -} -__name(setCredentialFeature, "setCredentialFeature"); +}; -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { + static { + __name(this, "NoAuthSigner"); } - context.__aws_sdk_context.features[feature] = value; -} -__name(setFeature, "setFeature"); + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +}; -// src/submodules/client/setTokenFeature.ts -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; } - token.$source[feature] = value; - return token; -} -__name(setTokenFeature, "setTokenFeature"); + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 97523: +/***/ 94747: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -46770,380 +33955,260 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/httpAuthSchemes/index.ts +// src/submodules/event-streams/index.ts var index_exports = {}; __export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties + EventStreamSerde: () => EventStreamSerde }); module.exports = __toCommonJS(index_exports); -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(17898); - -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts -var import_protocol_http = __nccwpck_require__(17898); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); - -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); - -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); - -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { - static { - __name(this, "AwsSdkSigV4Signer"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; +// src/submodules/event-streams/EventStreamSerde.ts +var import_schema = __nccwpck_require__(52290); +var import_util_utf8 = __nccwpck_require__(55969); +var EventStreamSerde = class { + /** + * Properties are injected by the HttpProtocol. + */ + constructor({ + marshaller, + serializer, + deserializer, + serdeContext, + defaultContentType + }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType } + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body + }; + } + for await (const page of eventStream) { + yield page; } } - throw error; }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -}; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(17898); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - static { - __name(this, "AwsSdkSigV4ASigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( + unionMember, + unionSchema, + event + ); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders + }; + return { + headers, + body + }; }); - return signedRequest; } -}; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), - /** - * Default auth scheme preference if not specified in environment or config + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream for the end-user. */ - default: [] -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(88180); -var import_property_provider = __nccwpck_require__(6180); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject + }; + } else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) + }; + } else { + return { + $unknown: event + }; + } }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(5152); -var import_core2 = __nccwpck_require__(88180); -var import_signature_v4 = __nccwpck_require__(75118); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error( + "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." + ); } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; } - } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + } + }; + } + /** + * @param unionMember - member name within the structure that contains an event stream union. + * @param unionSchema - schema of the union. + * @param event + * + * @returns the event body (bytes) and event type (string). + */ + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = unionSchema.hasMemberSchema(unionMember); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(import_schema.SCHEMA.DOCUMENT, value); } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } else { + type = "long"; + } + } else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } else if (memberSchema.isStringSchema()) { + type = "string"; + } else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } else { + serializer.write(eventSchema, event[unionMember]); + } + } else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } } + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders + }; } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); +}; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), -/***/ 37288: +/***/ 50678: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -47156,2356 +34221,2394 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/submodules/protocols/index.ts var index_exports = {}; __export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + HttpProtocol: () => HttpProtocol, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath }); module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts -var import_cbor = __nccwpck_require__(20695); -var import_schema2 = __nccwpck_require__(79724); +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(64356); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}; -// src/submodules/protocols/ProtocolLib.ts -var import_schema = __nccwpck_require__(79724); -var import_util_body_length_browser = __nccwpck_require__(24192); -var ProtocolLib = class { - static { - __name(this, "ProtocolLib"); +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +// src/submodules/protocols/HttpBindingProtocol.ts +var import_schema2 = __nccwpck_require__(52290); +var import_serde = __nccwpck_require__(24054); +var import_protocol_http2 = __nccwpck_require__(46572); +var import_util_stream2 = __nccwpck_require__(64356); + +// src/submodules/protocols/HttpProtocol.ts +var import_schema = __nccwpck_require__(52290); +var import_protocol_http = __nccwpck_require__(46572); +var HttpProtocol = class { + constructor(options) { + this.options = options; + } + getRequestType() { + return import_protocol_http.HttpRequest; + } + getResponseType() { + return import_protocol_http.HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + for (const [k, v] of endpoint.url.searchParams.entries()) { + if (!request.query) { + request.query = {}; + } + request.query[k] = v; + } + return request; + } else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const operationNs = import_schema.NormalizedSchema.of(operationSchema); + const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter( + ([, member]) => member.getMergedTraits().hostLabel + ); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }; } /** - * @param body - to be inspected. - * @param serdeContext - this is a subset type but in practice is the client.config having a property called bodyLengthChecker. + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). * - * @returns content-length value for the body if possible. - * @throws Error and should be caught and handled if not possible to determine length. + * @returns a stream suitable for the HTTP body of a request. */ - calculateContentLength(body, serdeContext) { - const bodyLengthCalculator = serdeContext?.bodyLengthChecker ?? import_util_body_length_browser.calculateBodyLength; - return String(bodyLengthCalculator(body)); + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }); } /** - * This is only for REST protocols. - * - * @param defaultContentType - of the protocol. - * @param inputSchema - schema for which to determine content type. + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). * - * @returns content-type header value or undefined when not applicable. + * @returns the asyncIterable of the event stream. */ - resolveRestContentType(defaultContentType, inputSchema) { - const members = inputSchema.getMemberSchemas(); - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - return mediaType; - } else if (httpPayloadMember.isStringSchema()) { - return "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - return "application/octet-stream"; - } else { - return defaultContentType; - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - const noPrefixHeaders = httpPrefixHeaders === void 0; - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; - }); - if (hasBody) { - return defaultContentType; - } - } } /** - * Shared code for finding error schema or throwing an unmodeled base error. - * @returns error schema and error metadata. - * - * @throws ServiceBaseException or generic Error if no error schema could be found. + * Loads eventStream capability async (for chunking). */ - async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { - let namespace = defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); + async loadEventStreamCapability() { + const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(94747))); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType() + }); + } + /** + * @returns content-type default header value for event stream events and other documents. + */ + getDefaultContentType() { + throw new Error( + `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` + ); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + void schema; + void context; + void response; + void arg4; + void arg5; + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); } - const errorMetadata = { - $metadata: metadata, - $response: response, - $fault: response.statusCode < 500 ? "client" : "server" + return context.eventStreamMarshaller; + } +}; + +// src/submodules/protocols/HttpBindingProtocol.ts +var HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ..._input ?? {} }; - const registry = import_schema.TypeRegistry.for(namespace); - try { - const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); - return { errorSchema, errorMetadata }; - } catch (e) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new import_protocol_http2.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); } - const baseExceptionSchema = import_schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns + }); + } + } else { + payload = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace( + `{${memberName}+}`, + replacement.split("/").map(extendedEncodeURIComponent).join("/") + ); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } else { + hasNonHttpBindingMember = true; + } + } + if (hasNonHttpBindingMember && input) { + serializer.write(schema, input); + payload = serializer.flush(); } + request.headers = headers; + request.query = query; + request.body = payload; + return request; } - /** - * Reads the x-amzn-query-error header for awsQuery compatibility. - * - * @param output - values that will be assigned to an error object. - * @param response - from which to read awsQueryError headers. - */ - setQueryCompatError(output, response) { - const queryErrorHeader = response.headers?.["x-amzn-query-error"]; - if (output !== void 0 && queryErrorHeader != null) { - const [Code, Type] = queryErrorHeader.split(";"); - const entries = Object.entries(output); - const Error2 = { - Code, - Type - }; - Object.assign(output, Error2); - for (const [k, v] of entries) { - Error2[k] = v; + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + // We pass on the traits to the sub-schema + // because we are still in the process of serializing the map itself. + ...traits, + httpQuery: key, + httpQueryParams: void 0 + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } } - delete Error2.__type; - output.Error = Error2; } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; } - /** - * Assigns Error, Type, Code from the awsQuery error object to the output error object. - * @param queryCompatErrorData - query compat error object. - * @param errorData - canonical error object returned to the caller. - */ - queryCompatOutput(queryCompatErrorData, errorData) { - if (queryCompatErrorData.Error) { - errorData.Error = queryCompatErrorData.Error; - } - if (queryCompatErrorData.Type) { - errorData.Type = queryCompatErrorData.Type; + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } else { + dataObject = arg4; } - if (queryCompatErrorData.Code) { - errorData.Code = queryCompatErrorData.Code; + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { + sections = (0, import_serde.splitEvery)(value, ",", 2); + } else { + sections = (0, import_serde.splitHeader)(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( + valueSchema, + value + ); + } + } + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } else { + nonHttpBindingMembers.push(memberName); + } } + return nonHttpBindingMembers; } }; -// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts -var AwsSmithyRpcV2CborProtocol = class extends import_cbor.SmithyRpcV2CborProtocol { - static { - __name(this, "AwsSmithyRpcV2CborProtocol"); - } - awsQueryCompatible; - mixin = new ProtocolLib(); - constructor({ - defaultNamespace, - awsQueryCompatible - }) { - super({ defaultNamespace }); - this.awsQueryCompatible = !!awsQueryCompatible; - } - /** - * @override - */ +// src/submodules/protocols/RpcProtocol.ts +var import_schema3 = __nccwpck_require__(52290); +var import_protocol_http3 = __nccwpck_require__(46572); +var RpcProtocol = class extends HttpProtocol { async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest + }); + } + } else { + serializer.write(schema, _input); + payload = serializer.flush(); + } } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; return request; } - /** - * @override - */ - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema3.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); } - const errorName = (0, import_cbor.loadSmithyRpcV2CborErrorCode)(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorName, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema2.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject + }); + } else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; } }; -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "number" || typeof val === "bigint") { - const warning = new Error(`Received number ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - if (typeof val === "boolean") { - const warning = new Error(`Received boolean ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - return val; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "number") { - } - if (typeof val === "string") { - const lowercase = val.toLowerCase(); - if (val !== "" && lowercase !== "false" && lowercase !== "true") { - const warning = new Error(`Received string "${val}" where a boolean was expected.`); - warning.name = "Warning"; - console.warn(warning); - } - return val !== "" && lowercase !== "false"; - } - return val; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; - } - if (typeof val === "boolean") { - } - if (typeof val === "string") { - const num = Number(val); - if (num.toString() !== val) { - const warning = new Error(`Received string "${val}" where a number was expected.`); - warning.name = "Warning"; - console.warn(warning); - return val; - } - return num; - } - return val; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols3 = __nccwpck_require__(97332); -var import_schema5 = __nccwpck_require__(79724); +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http4 = __nccwpck_require__(46572); -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); - } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); } + return resolvedPath2; }; -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_protocols = __nccwpck_require__(97332); -var import_schema3 = __nccwpck_require__(79724); -var import_serde2 = __nccwpck_require__(99628); -var import_util_base64 = __nccwpck_require__(96039); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(99628); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); } -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(61411); -var import_util_utf8 = __nccwpck_require__(60791); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_util_utf8.toUtf8)(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); } - return cleanValue; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); + return new import_protocol_http4.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; } -}, "loadRestJsonErrorCode"); - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; } - static { - __name(this, "JsonShapeDeserializer"); + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; } - readObject(schema, data) { - return this._read(schema, data); + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema3.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; + } +}; + +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var import_schema5 = __nccwpck_require__(52290); +var import_serde2 = __nccwpck_require__(24054); +var import_util_base64 = __nccwpck_require__(76249); +var import_util_utf8 = __nccwpck_require__(55969); + +// src/submodules/protocols/serde/determineTimestampFormat.ts +var import_schema4 = __nccwpck_require__(52290); +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { + return ns.getSchema(); } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; +} + +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var FromStringShapeDeserializer = class { + constructor(settings) { + this.settings = settings; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + read(_schema, data) { + const ns = import_schema5.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); } - if (ns.isTimestampSchema() && value != null) { - const format = (0, import_protocols.determineTimestampFormat)(ns, this.settings); + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); switch (format) { - case import_schema3.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema3.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); + case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); + case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(data); + case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(data); default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - const untyped = value; - if (untyped.type === "bigDecimal" && "string" in untyped) { - return new import_serde2.NumericValue(untyped.string, untyped.type); - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); } } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof import_serde2.NumericValue) { - out[k] = v; - } else { - out[k] = this._read(ns, v); - } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); } - return out; - } else { - return structuredClone(value); + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); + } + return intermediateValue; } } - return value; + switch (true) { + case ns.isNumericSchema(): + return Number(data); + case ns.isBigIntegerSchema(): + return BigInt(data); + case ns.isBigDecimalSchema(): + return new import_serde2.NumericValue(data, "bigDecimal"); + case ns.isBooleanSchema(): + return String(data).toLowerCase() === "true"; + } + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); } }; -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_protocols2 = __nccwpck_require__(97332); -var import_schema4 = __nccwpck_require__(79724); -var import_serde4 = __nccwpck_require__(99628); -var import_util_base642 = __nccwpck_require__(96039); - -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(99628); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { - static { - __name(this, "JsonReplacer"); +// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts +var import_schema6 = __nccwpck_require__(52290); +var import_util_utf82 = __nccwpck_require__(55969); +var HttpInterceptingShapeDeserializer = class { + constructor(codecDeserializer, codecSettings) { + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); } - /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. - */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; } - /** - * Replaces placeholder keys with their true values. - */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; + read(schema, data) { + const ns = import_schema6.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); } - for (const [key, value] of this.values) { - json = json.replace(key, value); + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } } - return json; + return this.codecDeserializer.read(ns, data); } }; -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var import_schema8 = __nccwpck_require__(52290); + +// src/submodules/protocols/serde/ToStringShapeSerializer.ts +var import_schema7 = __nccwpck_require__(52290); +var import_serde3 = __nccwpck_require__(24054); +var import_util_base642 = __nccwpck_require__(76249); +var ToStringShapeSerializer = class { constructor(settings) { - super(); this.settings = settings; + this.stringBuffer = ""; + this.serdeContext = void 0; } - static { - __name(this, "JsonShapeSerializer"); + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } - buffer; - rootSchema; write(schema, value) { - this.rootSchema = import_schema4.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); - } - /** - * @internal - */ - writeDiscriminatedDocument(schema, value) { - this.write(schema, value); - if (typeof this.buffer === "object") { - this.buffer.__type = import_schema4.NormalizedSchema.of(schema).getName(true); - } - } - flush() { - const { rootSchema } = this; - this.rootSchema = void 0; - if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema4.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); + const ns = import_schema7.NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error( + `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( + true + )}` + ); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: + this.stringBuffer = (0, import_serde3.dateToUtcString)(value); + break; + case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string") || ns.isDocumentSchema() && value instanceof Uint8Array) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - return (0, import_util_base642.toBase64)(value); - } - return this.serdeContext?.base64Encoder(value); + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); } - if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { - const format = (0, import_protocols2.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema4.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var HttpInterceptingShapeSerializer = class { + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = import_schema8.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== void 0) { + const buffer = this.buffer; + this.buffer = void 0; + return buffer; } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return (0, import_serde4.generateIdempotencyToken)(); + return this.codecSerializer.flush(); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 52290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/schema/index.ts +var index_exports = {}; +__export(index_exports, { + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + list: () => list, + map: () => map, + op: () => op, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + struct: () => struct +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/schema/deref.ts +var deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts +var import_protocol_http = __nccwpck_require__(46572); +var import_util_middleware = __nccwpck_require__(26252); +var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + try { + const parsed = await config.protocol.deserializeResponse( + operationSchema, + { + ...config, + ...context + }, + response + ); + return { + response, + output: parsed + }; + } catch (error2) { + Object.defineProperty(error2, "$response", { + value: response + }); + if (!("$metadata" in error2)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error2.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } } - const mediaType = ns.getMergedTraits().mediaType; - if (typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde4.LazyJsonString.from(value); + if (typeof error2.$responseBodyText !== "undefined") { + if (error2.$response) { + error2.$response.body = error2.$responseBodyText; } } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof import_serde4.NumericValue) { - out[k] = v; - } else { - out[k] = this._write(ns, v); - } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error2.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; } - return out; - } else { - return structuredClone(value); + } catch (e) { } } - return value; + throw error2; } }; +var findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonCodec"); - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } +// src/submodules/schema/middleware/schemaSerializationMiddleware.ts +var import_util_middleware2 = __nccwpck_require__(26252); +var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint + }); + return next({ + ...args, + request + }); }; -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols3.RpcProtocol { - static { - __name(this, "AwsJsonRpcProtocol"); - } - serializer; - deserializer; - serviceTarget; - codec; - mixin = new ProtocolLib(); - awsQueryCompatible; - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace - }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - this.awsQueryCompatible = !!awsQueryCompatible; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${import_schema5.NormalizedSchema.of(operationSchema).getName()}` - }); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - if ((0, import_schema5.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { +// src/submodules/schema/middleware/getSchemaSerdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); } - return request; + }; +} + +// src/submodules/schema/TypeRegistry.ts +var TypeRegistry = class _TypeRegistry { + constructor(namespace, schemas = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; } - getPayloadCodec() { - return this.codec; + static { + this.registries = /* @__PURE__ */ new Map(); } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema5.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); + /** + * @param namespace - specifier. + * @returns the schema for that namespace, creating it if necessary. + */ + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); + return _TypeRegistry.registries.get(namespace); } -}; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_0Protocol"); + /** + * Adds the given schema to a type registry with the same namespace. + * + * @param shapeId - to be registered. + * @param schema - to be registered. + */ + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = _TypeRegistry.for(this.getNamespace(shapeId)); + registry.schemas.set(qualifiedName, schema); } - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }); + /** + * @param shapeId - query. + * @returns the schema. + */ + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); } - getShapeId() { - return "aws.protocols#awsJson1_0"; + /** + * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, + * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which + * is unique per service/model. + * + * This is generated under a unique prefix that is combined with the service namespace, and this + * method is used to retrieve it. + * + * The base exception synthetic schema is used when an error is returned by a service, but we cannot + * determine what existing schema to use to deserialize it. + * + * @returns the synthetic base exception of the service namespace associated with this registry instance. + */ + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } + } + return void 0; } - getJsonRpcVersion() { - return "1.0"; + /** + * @param predicate - criterion. + * @returns a schema in this registry matching the predicate. + */ + find(predicate) { + return [...this.schemas.values()].find(predicate); } /** - * @override + * Unloads the current TypeRegistry. */ - getDefaultContentType() { - return "application/x-amz-json-1.0"; + destroy() { + _TypeRegistry.registries.delete(this.namespace); + this.schemas.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; } }; -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_1Protocol"); +// src/submodules/schema/schemas/Schema.ts +var Schema = class { + static assign(instance, values) { + const schema = Object.assign(instance, values); + TypeRegistry.for(schema.namespace).register(schema.name, schema); + return schema; } - constructor({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible - }); + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === this.symbol; + } + return isPrototype; } - getShapeId() { - return "aws.protocols#awsJson1_1"; + getName() { + return this.namespace + "#" + this.name; } - getJsonRpcVersion() { - return "1.1"; +}; + +// src/submodules/schema/schemas/ListSchema.ts +var ListSchema = class _ListSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _ListSchema.symbol; } - /** - * @override - */ - getDefaultContentType() { - return "application/x-amz-json-1.1"; + static { + this.symbol = Symbol.for("@smithy/lis"); } }; +var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema +}); -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols4 = __nccwpck_require__(97332); -var import_schema6 = __nccwpck_require__(79724); -var AwsRestJsonProtocol = class extends import_protocols4.HttpBindingProtocol { - static { - __name(this, "AwsRestJsonProtocol"); +// src/submodules/schema/schemas/MapSchema.ts +var MapSchema = class _MapSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _MapSchema.symbol; } - serializer; - deserializer; - codec; - mixin = new ProtocolLib(); - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols4.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols4.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + static { + this.symbol = Symbol.for("@smithy/map"); } - getShapeId() { - return "aws.protocols#restJson1"; +}; +var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema +}); + +// src/submodules/schema/schemas/OperationSchema.ts +var OperationSchema = class _OperationSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _OperationSchema.symbol; } - getPayloadCodec() { - return this.codec; + static { + this.symbol = Symbol.for("@smithy/ope"); } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); +}; +var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output +}); + +// src/submodules/schema/schemas/StructureSchema.ts +var StructureSchema = class _StructureSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _StructureSchema.symbol; } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema6.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - } - return request; + static { + this.symbol = Symbol.for("@smithy/str"); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata - ); - const ns = import_schema6.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); +}; +var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList +}); + +// src/submodules/schema/schemas/ErrorSchema.ts +var ErrorSchema = class _ErrorSchema extends StructureSchema { + constructor() { + super(...arguments); + this.symbol = _ErrorSchema.symbol; } - /** - * @override - */ - getDefaultContentType() { - return "application/json"; + static { + this.symbol = Symbol.for("@smithy/err"); } }; +var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor +}); -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(61411); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; +// src/submodules/schema/schemas/sentinels.ts +var SCHEMA = { + BLOB: 21, + // 21 + STREAMING_BLOB: 42, + // 42 + BOOLEAN: 2, + // 2 + STRING: 0, + // 0 + NUMERIC: 1, + // 1 + BIG_INTEGER: 17, + // 17 + BIG_DECIMAL: 19, + // 19 + DOCUMENT: 15, + // 15 + TIMESTAMP_DEFAULT: 4, + // 4 + TIMESTAMP_DATE_TIME: 5, + // 5 + TIMESTAMP_HTTP_DATE: 6, + // 6 + TIMESTAMP_EPOCH_SECONDS: 7, + // 7 + LIST_MODIFIER: 64, + // 64 + MAP_MODIFIER: 128 + // 128 +}; + +// src/submodules/schema/schemas/SimpleSchema.ts +var SimpleSchema = class _SimpleSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _SimpleSchema.symbol; } - if (typeof value === "object" && "__type" in value) { - delete value.__type; + static { + this.symbol = Symbol.for("@smithy/sim"); } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols7 = __nccwpck_require__(97332); -var import_schema9 = __nccwpck_require__(79724); +}; +var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef +}); -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols5 = __nccwpck_require__(97332); -var import_schema7 = __nccwpck_require__(79724); -var import_smithy_client3 = __nccwpck_require__(61411); -var import_util_utf82 = __nccwpck_require__(60791); -var import_fast_xml_parser = __nccwpck_require__(50591); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols5.FromStringShapeDeserializer(settings); +// src/submodules/schema/schemas/NormalizedSchema.ts +var NormalizedSchema = class _NormalizedSchema { + /** + * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. + * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. + */ + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + this.symbol = _NormalizedSchema.symbol; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema instanceof _NormalizedSchema) { + Object.assign(this, schema); + this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } } static { - __name(this, "XmlShapeDeserializer"); + this.symbol = Symbol.for("@smithy/nor"); } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); } /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. + * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. */ - read(schema, bytes, key) { - const ns = import_schema7.NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); + static of(ref) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + if (Array.isArray(ref)) { + const [ns, traits] = ref; + if (ns instanceof _NormalizedSchema) { + Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); + return ns; } - return output; + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema, key ? parsedObject[key] : parsedObject); + return new _NormalizedSchema(ref); } - readSchema(_schema, value) { - const ns = import_schema7.NormalizedSchema.of(_schema); - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; + /** + * @param indicator - numeric indicator for preset trait combination. + * @returns equivalent trait object. + */ + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer2 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer2.push(this.readSchema(listValue, v)); - } - } - return buffer2; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - if (value2 != null || sparse) { - buffer[key] = this.readSchema(memberNs, value2); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i++ & 1) === 1) { + traits[trait] = 1; } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); } - if (ns.isListSchema()) { - return []; + return traits; + } + /** + * @returns the underlying non-normalized schema. + */ + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + Object.assign(this, { schema: this.schema.getSchema() }); + return this.schema; } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); } - return this.stringDeserializer.read(ns, value); + return deref(this.schema); } - parseXml(xml) { - if (xml.length) { - const parser = new import_fast_xml_parser.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(xml, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; + /** + * @param withNamespace - qualifies the name. + * @returns e.g. `MyShape` or `com.namespace#MyShape`. + */ + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; } - return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); } - return {}; + return this.name || void 0; } -}; - -// src/submodules/protocols/query/QueryShapeSerializer.ts -var import_protocols6 = __nccwpck_require__(97332); -var import_schema8 = __nccwpck_require__(79724); -var import_serde5 = __nccwpck_require__(99628); -var import_smithy_client4 = __nccwpck_require__(61411); -var import_util_base643 = __nccwpck_require__(96039); -var QueryShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + /** + * @returns the member name if the schema is a member schema. + * @throws Error when the schema isn't a member schema. + */ + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + } + return this.memberName; } - static { - __name(this, "QueryShapeSerializer"); + isMemberSchema() { + return this._isMemberSchema; } - buffer; - write(schema, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; - } - const ns = import_schema8.NormalizedSchema.of(schema); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue((0, import_serde5.generateIdempotencyToken)()); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof import_serde5.NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = (0, import_protocols6.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: - this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); - break; - case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.writeValue(String(value.getTime() / 1e3)); - break; - } - } - } else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } + isUnitSchema() { + return this.getSchema() === "unit"; } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + /** + * boolean methods on this class help control flow in shape serialization and deserialization. + */ + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; } - const str = this.buffer; - delete this.buffer; - return str; + return inner instanceof ListSchema; } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; } - return key; + return inner instanceof MapSchema; } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${(0, import_protocols6.extendedEncodeURIComponent)(key)}=`; + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; } - writeValue(value) { - this.buffer += (0, import_protocols6.extendedEncodeURIComponent)(value); + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; } -}; - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var AwsQueryProtocol = class extends import_protocols7.RpcProtocol { - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); + isTimestampSchema() { + const schema = this.getSchema(); + return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; } - static { - __name(this, "AwsQueryProtocol"); + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; } - serializer; - deserializer; - mixin = new ProtocolLib(); - getShapeId() { - return "aws.protocols#awsQuery"; + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; + } + return this.getSchema() === SCHEMA.STREAMING_BLOB; + } + /** + * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. + * @returns whether the schema has the idempotencyToken trait. + */ + isIdempotencyToken() { + if (typeof this.traits === "number") { + return (this.traits & 4) === 4; + } else if (typeof this.traits === "object") { + return !!this.traits.idempotencyToken; + } + return false; + } + /** + * @returns own traits merged with member traits, where member traits of the same trait key take priority. + * This method is cached. + */ + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }); + } + /** + * @returns only the member traits. If the schema is not a member, this returns empty. + */ + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); + /** + * @returns only the traits inherent to the shape or member target shape if this schema is a member. + * If there are any member traits they are excluded. + */ + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` - }); - if ((0, import_schema9.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = ""; + /** + * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map or Document. + */ + getKeySchema() { + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); } - const action = operationSchema.name.split("#")[1] ?? operationSchema.name; - request.body = `Action=${action}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); } - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { + const schema = this.getSchema(); + if (typeof schema === "number") { + return this.memberFrom([63 & schema, 0], "key"); } - return request; + return this.memberFrom([schema.keySchema, 0], "key"); } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema9.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await (0, import_protocols7.collectBody)(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema9.SCHEMA.DOCUMENT, bytes2)); + /** + * @returns the schema of the map's value or list's member. + * Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map, List, nor Document. + */ + getValueSchema() { + const schema = this.getSchema(); + if (typeof schema === "number") { + if (this.isMapSchema()) { + return this.memberFrom([63 & schema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([63 & schema, 0], "member"); } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; + if (schema && typeof schema === "object") { + if (this.isStructSchema()) { + throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + } + const collection = schema; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return this.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([collection.valueSchema, 0], "member"); + } + } } - const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; - const bytes = await (0, import_protocols7.collectBody)(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); } /** - * EC2 Query overrides this. + * @param member - to query. + * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). */ - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - const errorData = this.loadQueryError(dataObject); - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - errorData, - metadata, - (registry, errorName) => registry.find( - (schema) => import_schema9.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName - ) - ); - const ns = import_schema9.NormalizedSchema.of(errorSchema); - const message = this.loadQueryErrorMessage(dataObject); - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorData[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); + hasMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + return struct2.memberNames.includes(member); } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); + return false; } /** - * The variations in the error and error message locations are attributed to - * divergence between AWS Query and EC2 Query behavior. + * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` + * and will have the member name given. + * @param member - which member to retrieve and wrap. + * + * @throws Error if member does not exist or the schema is neither a document nor structure. + * Note that errors are assumed to be structures and unions are considered structures for these purposes. */ - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== void 0) { - return code; + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + if (!struct2.memberNames.includes(member)) { + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); + } + const i = struct2.memberNames.indexOf(member); + const memberSchema = struct2.memberList[i]; + return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); } - if (output.statusCode == 404) { - return "NotFound"; + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], member); } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; - } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; - } - /** - * @override - */ - getDefaultContentType() { - return "application/x-www-form-urlencoded"; - } -}; - -// src/submodules/protocols/query/AwsEc2QueryProtocol.ts -var AwsEc2QueryProtocol = class extends AwsQueryProtocol { - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false - }; - Object.assign(this.serializer.settings, ec2Settings); - } - static { - __name(this, "AwsEc2QueryProtocol"); + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); } /** - * EC2 Query reads XResponse.XResult instead of XResponse directly. + * This can be used for checking the members as a hashmap. + * Prefer the structIterator method for iteration. + * + * This does NOT return list and map members, it is only for structures. + * + * @deprecated use (checked) structIterator instead. + * + * @returns a map of member names to member schemas (normalized). */ - useNestedResult() { - return false; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var import_protocols9 = __nccwpck_require__(97332); -var import_schema11 = __nccwpck_require__(79724); - -// src/submodules/protocols/xml/parseXmlBody.ts -var import_smithy_client5 = __nccwpck_require__(61411); -var import_fast_xml_parser2 = __nccwpck_require__(50591); -var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - const parser = new import_fast_xml_parser2.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; + getMemberSchemas() { + const buffer = {}; try { - parsedObj = parser.parse(encoded, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); + for (const [k, v] of this.structIterator()) { + buffer[k] = v; } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; + } catch (ignored) { } - return (0, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); - } - return {}; -}), "parseXmlBody"); -var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}, "parseXmlErrorBody"); -var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data?.Error?.Code !== void 0) { - return data.Error.Code; - } - if (data?.Code !== void 0) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadRestXmlErrorCode"); - -// src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(94274); -var import_protocols8 = __nccwpck_require__(97332); -var import_schema10 = __nccwpck_require__(79724); -var import_serde6 = __nccwpck_require__(99628); -var import_smithy_client6 = __nccwpck_require__(61411); -var import_util_base644 = __nccwpck_require__(96039); -var XmlShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlShapeSerializer"); + return buffer; } - stringBuffer; - byteBuffer; - buffer; - write(schema, value) { - const ns = import_schema10.NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base644.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); + /** + * @returns member name of event stream or empty string indicating none exists or this + * isn't a structure schema. + */ + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } } } + return ""; } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; + /** + * Allows iteration over members of a structure schema. + * Each yield is a pair of the member name and member schema. + * + * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). + */ + *structIterator() { + if (this.isUnitSchema()) { + return; } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } + const struct2 = this.getSchema(); + for (let i = 0; i < struct2.memberNames.length; ++i) { + yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } - delete this.buffer; - return buffer.toString(); } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( - true - )}.` - ); - } - const structXmlNode = import_xml_builder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute( - memberSchema.getMergedTraits().xmlName ?? memberName, - this.writeSimple(memberSchema, val) - ); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); + /** + * Creates a normalized member schema from the given schema and member name. + */ + memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); } - return structXmlNode; + return new _NormalizedSchema(memberSchema, memberName); } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` - ); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = /* @__PURE__ */ __name((container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode( - struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") - ); - } else { - const listItemNode = import_xml_builder.XmlNode.of( - flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" - ); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }, "writeItem"); - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } + /** + * @returns a last-resort human-readable name for the schema if it has no other identifiers. + */ + getSchemaName() { + const schema = this.getSchema(); + if (typeof schema === "number") { + const _schema = 63 & schema; + const container = 192 & schema; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; } - container.addChildNode(listNode); } + return "Unknown"; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 24054: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/serde/index.ts +var index_exports = {}; +__export(index_exports, { + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger, + nv: () => nv, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/serde/copyDocumentWithTransform.ts +var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; + +// src/submodules/serde/parse-utils.ts +var parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` - ); +}; +var expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { - const keyNode = import_xml_builder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }, "addKeyValue"); - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } + if (value === 0) { + return false; + } + if (value === 1) { + return true; } } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - const ns = import_schema10.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base644.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const format = (0, import_protocols8.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema10.SCHEMA.TIMESTAMP_DATE_TIME: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema10.SCHEMA.TIMESTAMP_HTTP_DATE: - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - case import_schema10.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof import_serde6.NumericValue) { - return value.string; - } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error( - "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." - ); - } else { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( - true - )}` - ); - } + if (lower === "false") { + return false; } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); + if (lower === "true") { + return true; } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { - nodeContents = (0, import_serde6.generateIdempotencyToken)(); - } else { - nodeContents = String(value); + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +var expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } + return parsed; } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = import_schema10.NormalizedSchema.of(_schema); - const content = new import_xml_builder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); } - into.addChildNode(content); } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + return expected; +}; +var expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +var expectInt = expectLong; +var expectInt32 = (value) => expectSizedInt(value, 32); +var expectShort = (value) => expectSizedInt(value, 16); +var expectByte = (value) => expectSizedInt(value, 8); +var expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +var castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +var expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); } - return [void 0, void 0]; + throw new TypeError("Expected a non-null value"); } + return value; }; - -// src/submodules/protocols/xml/XmlCodec.ts -var XmlCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; +var expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; } - static { - __name(this, "XmlCodec"); + if (typeof value === "object" && !Array.isArray(value)) { + return value; } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +var expectString = (value) => { + if (value === null || value === void 0) { + return void 0; } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +var expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +var strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +var limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +var parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +var strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +var strictParseInt = strictParseLong; +var strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +var strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +var strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); } + return expectByte(value); +}; +var stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}; +var logger = { + warn: console.warn }; -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var AwsRestXmlProtocol = class extends import_protocols9.HttpBindingProtocol { - static { - __name(this, "AwsRestXmlProtocol"); +// src/submodules/serde/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; } - codec; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema11.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace - }; - this.codec = new XmlCodec(settings); - this.serializer = new import_protocols9.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols9.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - getPayloadCodec() { - return this.codec; + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); } - getShapeId() { - return "aws.protocols#restXml"; + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema11.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - if (request.body) { - try { - request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); - } catch (e) { - } - } - return request; + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( - errorIdentifier, - this.options.defaultNamespace, - response, - dataObject, - metadata + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } ); - const ns = import_schema11.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); - } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) ); } - /** - * @override - */ - getDefaultContentType() { - return "application/xml"; + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); } + throw new TypeError("Invalid RFC-7231 date-time value"); }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 88180: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +var parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}; +var parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; } - return to; + return valueInThisCentury; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(34048); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(56182); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } - } + return input; +}; +var parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } + return monthIdx + 1; +}; +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; } - return preferredAuthOptions; -}, "resolveAuthOptions"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } - return map; -} -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; +}; +var isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +var parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); + return dateVal; +}; +var parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" + return strictParseFloat32("0." + value) * 1e3; }; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(88037); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +var parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; }; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemePlugin"); - -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(17898); - -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); +var stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + if (idx === 0) { + return value; } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); - -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" + return value.slice(idx); }; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); - }, "applyToStack") -}), "getHttpSigningPlugin"); -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); +// src/submodules/serde/generateIdempotencyToken.ts +var import_uuid = __nccwpck_require__(12048); -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; +// src/submodules/serde/lazy-json.ts +var LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); } - cursor = cursor[step]; + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); } - return cursor; -}, "get"); - -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(97332); + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; +// src/submodules/serde/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; } - context.__smithy_context.features[feature] = value; + return part; } -__name(setFeature, "setFeature"); -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } - } - } - static { - __name(this, "DefaultIdentityProviderConfig"); - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); +// src/submodules/serde/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { - static { - __name(this, "HttpApiKeyAuthSigner"); + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); + currentSegment += delimiter + segments[i]; } - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts - -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } -}; - -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; + if (currentSegment !== "") { + compoundSegments.push(currentSegment); } -}; + return compoundSegments; +} -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; +// src/submodules/serde/split-header.ts +var splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + default: + } + prevChar = char; } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); + return v.replace(/\\"/g, '"'); + }); +}; + +// src/submodules/serde/value/NumericValue.ts +var NumericValue = class _NumericValue { + constructor(string, type) { + this.string = string; + this.type = type; + let dot = 0; + for (let i = 0; i < string.length; ++i) { + const char = string.charCodeAt(i); + if (i === 0 && char === 45) { + continue; + } + if (char === 46) { + if (dot) { + throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); + } + dot = 1; + continue; + } + if (char < 48 || char > 57) { + throw new Error( + `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` + ); } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); } - if (isConstant) { - return resolved; + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; + const _nv = object; + const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); + if (prototypeMatch) { + return prototypeMatch; } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; + if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { + return true; } - return resolved; - }; -}, "memoizeIdentityProvider"); + return prototypeMatch; + } +}; +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 20695: +/***/ 90793: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -49520,1323 +36623,1704 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/cbor/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - CborCodec: () => CborCodec, - CborShapeDeserializer: () => CborShapeDeserializer, - CborShapeSerializer: () => CborShapeSerializer, - SmithyRpcV2CborProtocol: () => SmithyRpcV2CborProtocol, - buildHttpRpcRequest: () => buildHttpRpcRequest, - cbor: () => cbor, - checkCborResponse: () => checkCborResponse, - dateToTag: () => dateToTag, - loadSmithyRpcV2CborErrorCode: () => loadSmithyRpcV2CborErrorCode, - parseCborBody: () => parseCborBody, - parseCborErrorBody: () => parseCborErrorBody, - tag: () => tag, - tagSymbol: () => tagSymbol + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/submodules/cbor/cbor-decode.ts -var import_serde = __nccwpck_require__(99628); -var import_util_utf8 = __nccwpck_require__(60791); +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(46572); +var import_querystring_builder = __nccwpck_require__(36600); -// src/submodules/cbor/cbor-types.ts -var majorUint64 = 0; -var majorNegativeInt64 = 1; -var majorUnstructuredByteString = 2; -var majorUtf8String = 3; -var majorList = 4; -var majorMap = 5; -var majorTag = 6; -var majorSpecial = 7; -var specialFalse = 20; -var specialTrue = 21; -var specialNull = 22; -var specialUndefined = 23; -var extendedOneByte = 24; -var extendedFloat16 = 25; -var extendedFloat32 = 26; -var extendedFloat64 = 27; -var minorIndefinite = 31; -function alloc(size) { - return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); -} -var tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); -function tag(data2) { - data2[tagSymbol] = true; - return data2; +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); } +__name(createRequest, "createRequest"); -// src/submodules/cbor/cbor-decode.ts -var USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; -var USE_BUFFER = typeof Buffer !== "undefined"; -var payload = alloc(0); -var dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -var textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; -var _offset = 0; -function setPayload(bytes) { - payload = bytes; - dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); } -function decode(at, to) { - if (at >= to) { - throw new Error("unexpected end of (decode) payload."); +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { + static { + __name(this, "FetchHttpHandler"); } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - switch (major) { - case majorUint64: - case majorNegativeInt64: - case majorTag: - let unsignedInt; - let offset; - if (minor < 24) { - unsignedInt = minor; - offset = 1; - } else { - switch (minor) { - case extendedOneByte: - case extendedFloat16: - case extendedFloat32: - case extendedFloat64: - const countLength = minorValueToArgumentLength[minor]; - const countOffset = countLength + 1; - offset = countOffset; - if (to - at < countOffset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - unsignedInt = payload[countIndex]; - } else if (countLength === 2) { - unsignedInt = dataView.getUint16(countIndex); - } else if (countLength === 4) { - unsignedInt = dataView.getUint32(countIndex); - } else { - unsignedInt = dataView.getBigUint64(countIndex); - } - break; - default: - throw new Error(`unexpected minor value ${minor}.`); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; } - } - if (major === majorUint64) { - _offset = offset; - return castBigInt(unsignedInt); - } else if (major === majorNegativeInt64) { - let negativeInt; - if (typeof unsignedInt === "bigint") { - negativeInt = BigInt(-1) - unsignedInt; - } else { - negativeInt = -1 - unsignedInt; + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); } - _offset = offset; - return castBigInt(negativeInt); - } else { - if (minor === 2 || minor === 3) { - const length = decodeCount(at + offset, to); - let b = BigInt(0); - const start = at + offset + _offset; - for (let i = start; i < start + length; ++i) { - b = b << BigInt(8) | BigInt(payload[i]); - } - _offset = offset + _offset + length; - return minor === 3 ? -b - BigInt(1) : b; - } else if (minor === 4) { - const decimalFraction = decode(at + offset, to); - const [exponent, mantissa] = decimalFraction; - const normalizer = mantissa < 0 ? -1 : 1; - const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); - let numericString; - const sign = mantissa < 0 ? "-" : ""; - numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); - numericString = numericString.replace(/^0+/g, ""); - if (numericString === "") { - numericString = "0"; - } - if (numericString[0] === ".") { - numericString = "0" + numericString; + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; } - numericString = sign + numericString; - _offset = offset + _offset; - return (0, import_serde.nv)(numericString); - } else { - const value = decode(at + offset, to); - const valueOffset = _offset; - _offset = offset + valueOffset; - return tag({ tag: castBigInt(unsignedInt), value }); - } - } - case majorUtf8String: - case majorMap: - case majorList: - case majorUnstructuredByteString: - if (minor === minorIndefinite) { - switch (major) { - case majorUtf8String: - return decodeUtf8StringIndefinite(at, to); - case majorMap: - return decodeMapIndefinite(at, to); - case majorList: - return decodeListIndefinite(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteStringIndefinite(at, to); - } - } else { - switch (major) { - case majorUtf8String: - return decodeUtf8String(at, to); - case majorMap: - return decodeMap(at, to); - case majorList: - return decodeList(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteString(at, to); - } - } - default: - return decodeSpecial(at, to); + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(76249); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; } + return collected; } -function bytesToUtf8(bytes, at, to) { - if (USE_BUFFER && bytes.constructor?.name === "Buffer") { - return bytes.toString("utf-8", at, to); - } - if (textDecoder) { - return textDecoder.decode(bytes.subarray(at, to)); - } - return (0, import_util_utf8.toUtf8)(bytes.subarray(at, to)); +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); } -function demote(bigInteger) { - const num = Number(bigInteger); - if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { - console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); +__name(readToBase64, "readToBase64"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 56186: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return num; -} -var minorValueToArgumentLength = { - [extendedOneByte]: 1, - [extendedFloat16]: 2, - [extendedFloat32]: 4, - [extendedFloat64]: 8 + return to; }; -function bytesToFloat16(a, b) { - const sign = a >> 7; - const exponent = (a & 124) >> 2; - const fraction = (a & 3) << 8 | b; - const scalar = sign === 0 ? 1 : -1; - let exponentComponent; - let summation; - if (exponent === 0) { - if (fraction === 0) { - return 0; - } else { - exponentComponent = Math.pow(2, 1 - 15); - summation = 0; - } - } else if (exponent === 31) { - if (fraction === 0) { - return scalar * Infinity; - } else { - return NaN; - } - } else { - exponentComponent = Math.pow(2, exponent - 15); - summation = 1; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(index_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 57217: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEndpointFromConfig = void 0; +const node_config_provider_1 = __nccwpck_require__(50240); +const getEndpointUrlConfig_1 = __nccwpck_require__(6416); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; + + +/***/ }), + +/***/ 6416: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEndpointUrlConfig = void 0; +const shared_ini_file_loader_1 = __nccwpck_require__(56700); +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (config && profile.services) { + const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); +exports.getEndpointUrlConfig = getEndpointUrlConfig; + + +/***/ }), + +/***/ 88075: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - summation += fraction / 1024; - return scalar * (exponentComponent * summation); -} -function decodeCount(at, to) { - const minor = payload[at] & 31; - if (minor < 24) { - _offset = 1; - return minor; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + endpointMiddleware: () => endpointMiddleware, + endpointMiddlewareOptions: () => endpointMiddlewareOptions, + getEndpointFromInstructions: () => getEndpointFromInstructions, + getEndpointPlugin: () => getEndpointPlugin, + resolveEndpointConfig: () => resolveEndpointConfig, + resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, + resolveParams: () => resolveParams, + toEndpointV1: () => toEndpointV1 +}); +module.exports = __toCommonJS(index_exports); + +// src/service-customizations/s3.ts +var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); } - if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) { - const countLength = minorValueToArgumentLength[minor]; - _offset = countLength + 1; - if (to - at < _offset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - return payload[countIndex]; - } else if (countLength === 2) { - return dataView.getUint16(countIndex); - } else if (countLength === 4) { - return dataView.getUint32(countIndex); + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); } - return demote(dataView.getBigUint64(countIndex)); - } - throw new Error(`unexpected minor value ${minor}.`); -} -function decodeUtf8String(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`string len ${length} greater than remaining buf len.`); + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; } - const value = bytesToUtf8(payload, at, at + length); - _offset = offset + length; - return value; -} -function decodeUtf8StringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector.length); - data2.set(vector, 0); - _offset = at - base + 2; - return bytesToUtf8(data2, 0, data2.length); - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); - } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; } - throw new Error("expected break marker."); -} -function decodeUnstructuredByteString(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); + return endpointParams; +}, "resolveParamsForS3"); +var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +var DOTS_PATTERN = /\.\./; +var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); +var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } - const value = payload.subarray(at, at + length); - _offset = offset + length; - return value; -} -function decodeUnstructuredByteStringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector.length); - data2.set(vector, 0); - _offset = at - base + 2; - return data2; - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUnstructuredByteString) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); + return isValidArn; +}, "isArnBucketName"); + +// src/adaptors/createConfigValueProvider.ts +var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { + const configProvider = /* @__PURE__ */ __name(async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); } + return configValue; + }, "configProvider"); + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; } - throw new Error("expected break marker."); -} -function decodeList(at, to) { - const listDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const list = Array(listDataLength); - for (let i = 0; i < listDataLength; ++i) { - const item = decode(at, to); - const itemOffset = _offset; - list[i] = item; - at += itemOffset; + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; } - _offset = offset + (at - base); - return list; -} -function decodeListIndefinite(at, to) { - at += 1; - const list = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - _offset = at - base + 2; - return list; - } - const item = decode(at, to); - const n = _offset; - at += n; - list.push(item); + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return void 0; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; } - throw new Error("expected break marker."); -} -function decodeMap(at, to) { - const mapDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const map = {}; - for (let i = 0; i < mapDataLength; ++i) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key at index ${at}.`); + return configProvider; +}, "createConfigValueProvider"); + +// src/adaptors/getEndpointFromInstructions.ts +var import_getEndpointFromConfig = __nccwpck_require__(57217); + +// src/adaptors/toEndpointV1.ts +var import_url_parser = __nccwpck_require__(38006); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return (0, import_url_parser.parseUrl)(endpoint.url); } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; + return endpoint; } - _offset = offset + (at - base); - return map; -} -function decodeMapIndefinite(at, to) { - at += 1; - const base = at; - const map = {}; - for (; at < to; ) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - if (payload[at] === 255) { - _offset = at - base + 2; - return map; + return (0, import_url_parser.parseUrl)(endpoint); +}, "toEndpointV1"); + +// src/adaptors/getEndpointFromInstructions.ts +var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key.`); + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; } - throw new Error("expected break marker."); -} -function decodeSpecial(at, to) { - const minor = payload[at] & 31; - switch (minor) { - case specialTrue: - case specialFalse: - _offset = 1; - return minor === specialTrue; - case specialNull: - _offset = 1; - return null; - case specialUndefined: - _offset = 1; - return null; - case extendedFloat16: - if (to - at < 3) { - throw new Error("incomplete float16 at end of buf."); - } - _offset = 3; - return bytesToFloat16(payload[at + 1], payload[at + 2]); - case extendedFloat32: - if (to - at < 5) { - throw new Error("incomplete float32 at end of buf."); - } - _offset = 5; - return dataView.getFloat32(at + 1); - case extendedFloat64: - if (to - at < 9) { - throw new Error("incomplete float64 at end of buf."); - } - _offset = 9; - return dataView.getFloat64(at + 1); - default: - throw new Error(`unexpected minor value ${minor}.`); + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; +}, "getEndpointFromInstructions"); +var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } } -} -function castBigInt(bigInt) { - if (typeof bigInt === "number") { - return bigInt; + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); } - const num = Number(bigInt); - if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { - return num; + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); } - return bigInt; -} + return endpointParams; +}, "resolveParams"); -// src/submodules/cbor/cbor-encode.ts -var import_serde2 = __nccwpck_require__(99628); -var import_util_utf82 = __nccwpck_require__(60791); -var USE_BUFFER2 = typeof Buffer !== "undefined"; -var initialSize = 2048; -var data = alloc(initialSize); -var dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); -var cursor = 0; -function ensureSpace(bytes) { - const remaining = data.byteLength - cursor; - if (remaining < bytes) { - if (cursor < 16e6) { - resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); - } else { - resize(data.byteLength + bytes + 16e6); +// src/endpointMiddleware.ts +var import_core = __nccwpck_require__(3402); +var import_util_middleware = __nccwpck_require__(26252); +var endpointMiddleware = /* @__PURE__ */ __name(({ + config, + instructions +}) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); } - } -} -function toUint8Array() { - const out = alloc(cursor); - out.set(data.subarray(0, cursor), 0); - cursor = 0; - return out; -} -function resize(size) { - const old = data; - data = alloc(size); - if (old) { - if (old.copy) { - old.copy(data, 0, 0, old.byteLength); - } else { - data.set(old, 0); + const endpoint = await getEndpointFromInstructions( + args.input, + { + getEndpointParameterInstructions() { + return instructions; + } + }, + { ...config }, + context + ); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign( + httpAuthOption.signingProperties || {}, + { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet + }, + authScheme.properties + ); + } + } + return next({ + ...args + }); + }; +}, "endpointMiddleware"); + +// src/getEndpointPlugin.ts +var import_middleware_serde = __nccwpck_require__(4783); +var endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + endpointMiddleware({ + config, + instructions + }), + endpointMiddlewareOptions + ); + }, "applyToStack") +}), "getEndpointPlugin"); + +// src/resolveEndpointConfig.ts + +var import_getEndpointFromConfig2 = __nccwpck_require__(57217); +var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), + useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); } + return configuredEndpointPromise; + }; + return resolvedConfig; +}, "resolveEndpointConfig"); + +// src/resolveEndpointRequiredConfig.ts +var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + throw new Error( + "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." + ); + }; } - dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); -} -function encodeHeader(major, value) { - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 1 << 8) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 1 << 16) { - data[cursor++] = major << 5 | extendedFloat16; - dataView2.setUint16(cursor, value); - cursor += 2; - } else if (value < 2 ** 32) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; - } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); - cursor += 8; + return input; +}, "resolveEndpointRequiredConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 4783: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } -} -function encode(_input) { - const encodeStack = [_input]; - while (encodeStack.length) { - const input = encodeStack.pop(); - ensureSpace(typeof input === "string" ? input.length * 4 : 64); - if (typeof input === "string") { - if (USE_BUFFER2) { - encodeHeader(majorUtf8String, Buffer.byteLength(input)); - cursor += data.write(input, cursor); - } else { - const bytes = (0, import_util_utf82.fromUtf8)(input); - encodeHeader(majorUtf8String, bytes.byteLength); - data.set(bytes, cursor); - cursor += bytes.byteLength; - } - continue; - } else if (typeof input === "number") { - if (Number.isInteger(input)) { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - 1; - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = value >> 8; - data[cursor++] = value; - } else if (value < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption +}); +module.exports = __toCommonJS(index_exports); + +// src/deserializerMiddleware.ts +var import_protocol_http = __nccwpck_require__(46572); +var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, BigInt(value)); - cursor += 8; + context.logger?.warn?.(hint); } - continue; } - data[cursor++] = majorSpecial << 5 | extendedFloat64; - dataView2.setFloat64(cursor, input); - cursor += 8; - continue; - } else if (typeof input === "bigint") { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - BigInt(1); - const n = Number(value); - if (n < 24) { - data[cursor++] = major << 5 | n; - } else if (n < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = n; - } else if (n < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = n >> 8; - data[cursor++] = n & 255; - } else if (n < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, n); - cursor += 4; - } else if (value < BigInt("18446744073709551616")) { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, value); - cursor += 8; - } else { - const binaryBigInt = value.toString(2); - const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); - let b = value; - let i = 0; - while (bigIntBytes.byteLength - ++i >= 0) { - bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); - b >>= BigInt(8); - } - ensureSpace(bigIntBytes.byteLength * 2); - data[cursor++] = nonNegative ? 194 : 195; - if (USE_BUFFER2) { - encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); - } else { - encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; } - data.set(bigIntBytes, cursor); - cursor += bigIntBytes.byteLength; - } - continue; - } else if (input === null) { - data[cursor++] = majorSpecial << 5 | specialNull; - continue; - } else if (typeof input === "boolean") { - data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse); - continue; - } else if (typeof input === "undefined") { - throw new Error("@smithy/core/cbor: client may not serialize undefined value."); - } else if (Array.isArray(input)) { - for (let i = input.length - 1; i >= 0; --i) { - encodeStack.push(input[i]); - } - encodeHeader(majorList, input.length); - continue; - } else if (typeof input.byteLength === "number") { - ensureSpace(input.length * 2); - encodeHeader(majorUnstructuredByteString, input.length); - data.set(input, cursor); - cursor += input.byteLength; - continue; - } else if (typeof input === "object") { - if (input instanceof import_serde2.NumericValue) { - const decimalIndex = input.string.indexOf("."); - const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; - const mantissa = BigInt(input.string.replace(".", "")); - data[cursor++] = 196; - encodeStack.push(mantissa); - encodeStack.push(exponent); - encodeHeader(majorList, 2); - continue; } - if (input[tagSymbol]) { - if ("tag" in input && "value" in input) { - encodeStack.push(input.value); - encodeHeader(majorTag, input.tag); - continue; - } else { - throw new Error( - "tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input) - ); + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; } + } catch (e) { } - const keys = Object.keys(input); - for (let i = keys.length - 1; i >= 0; --i) { - const key = keys[i]; - encodeStack.push(input[key]); - encodeStack.push(key); - } - encodeHeader(majorMap, keys.length); - continue; } - throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); + throw error; + } +}, "deserializerMiddleware"); +var findHeader = /* @__PURE__ */ __name((pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}, "findHeader"); + +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); + +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: /* @__PURE__ */ __name((commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, "applyToStack") + }; +} +__name(getSerdePlugin, "getSerdePlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 50240: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + loadConfig: () => loadConfig +}); +module.exports = __toCommonJS(index_exports); + +// src/configLoader.ts + + +// src/fromEnv.ts +var import_property_provider = __nccwpck_require__(74558); + +// src/getSelectorName.ts +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } catch (e) { + return functionString; + } +} +__name(getSelectorName, "getSelectorName"); + +// src/fromEnv.ts +var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === void 0) { + throw new Error(); + } + return config; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, + { logger: options?.logger } + ); + } +}, "fromEnv"); + +// src/fromSharedConfigFiles.ts + +var import_shared_ini_file_loader = __nccwpck_require__(56700); +var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = (0, import_shared_ini_file_loader.getProfileName)(init); + const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === void 0) { + throw new Error(); + } + return configValue; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, + { logger: init.logger } + ); } -} +}, "fromSharedConfigFiles"); -// src/submodules/cbor/cbor.ts -var cbor = { - deserialize(payload2) { - setPayload(payload2); - return decode(0, payload2.length); - }, - serialize(input) { - try { - encode(input); - return toUint8Array(); - } catch (e) { - toUint8Array(); - throw e; - } - }, - /** - * @public - * @param size - byte length to allocate. - * - * This may be used to garbage collect the CBOR - * shared encoding buffer space, - * e.g. resizeEncodingBuffer(0); - * - * This may also be used to pre-allocate more space for - * CBOR encoding, e.g. resizeEncodingBuffer(100_000_000); - */ - resizeEncodingBuffer(size) { - resize(size); +// src/fromStatic.ts + +var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); +var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); + +// src/configLoader.ts +var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + fromEnv(environmentVariableSelector, envOptions), + fromSharedConfigFiles(configFileSelector, configuration), + fromStatic(defaultValue) + ) + ); +}, "loadConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 60967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/cbor/parseCborBody.ts -var import_protocols = __nccwpck_require__(97332); -var import_protocol_http = __nccwpck_require__(17898); -var import_util_body_length_browser = __nccwpck_require__(24192); -var parseCborBody = (streamBody, context) => { - return (0, import_protocols.collectBody)(streamBody, context).then(async (bytes) => { - if (bytes.length) { - try { - return cbor.deserialize(bytes); - } catch (e) { - Object.defineProperty(e, "$responseBodyText", { - value: context.utf8Encoder(bytes) +// src/index.ts +var index_exports = {}; +__export(index_exports, { + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(index_exports); + +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(46572); +var import_querystring_builder = __nccwpck_require__(36600); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); + +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); + +// src/timing.ts +var timing = { + setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), + clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); }); - throw e; + } else { + timing.clearTimeout(timeoutId); } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); } - return {}; - }); -}; -var dateToTag = (date) => { - return tag({ - tag: 1, - value: date.getTime() / 1e3 - }); -}; -var parseCborErrorBody = async (errorBody, context) => { - const value = await parseCborBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}; -var loadSmithyRpcV2CborErrorCode = (output, data2) => { - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - if (data2["__type"] !== void 0) { - return sanitizeErrorCode(data2["__type"]); - } - const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code"); - if (codeKey && data2[codeKey] !== void 0) { - return sanitizeErrorCode(data2[codeKey]); + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; } -}; -var checkCborResponse = (response) => { - if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { - throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; } -}; -var buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers: { - // intentional copy. - ...headers + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); } - }; - if (resolvedHostname !== void 0) { - contents.hostname = resolvedHostname; + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; } - if (body !== void 0) { - contents.body = body; - try { - contents.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(body)); - } catch (e) { + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; } - return new import_protocol_http.HttpRequest(contents); -}; - -// src/submodules/cbor/SmithyRpcV2CborProtocol.ts -var import_protocols2 = __nccwpck_require__(97332); -var import_schema2 = __nccwpck_require__(79724); -var import_util_middleware = __nccwpck_require__(56182); + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); -// src/submodules/cbor/CborCodec.ts -var import_schema = __nccwpck_require__(79724); -var import_serde3 = __nccwpck_require__(99628); -var import_util_base64 = __nccwpck_require__(96039); -var CborCodec = class { - createSerializer() { - const serializer = new CborShapeSerializer(); - serializer.setSerdeContext(this.serdeContext); - return serializer; +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); } - createDeserializer() { - const deserializer = new CborShapeDeserializer(); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; + if (sendBody) { + writeBody(httpRequest, request.body); } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; } -}; -var CborShapeSerializer = class { - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; } - write(schema, value) { - this.value = this.serialize(schema, value); + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + static { + __name(this, "NodeHttpHandler"); } /** - * Recursive serializer transform that copies and prepares the user input object - * for CBOR serialization. + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. */ - serialize(schema, source) { - const ns = import_schema.NormalizedSchema.of(schema); - if (source == null) { - if (ns.isIdempotencyToken()) { - return (0, import_serde3.generateIdempotencyToken)(); - } - return source; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - if (ns.isBlobSchema()) { - if (typeof source === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(source); - } - return source; + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; } - if (ns.isTimestampSchema()) { - if (typeof source === "number" || typeof source === "bigint") { - return dateToTag(new Date(Number(source) / 1e3 | 0)); - } - return dateToTag(source); + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; } - if (typeof source === "function" || typeof source === "object") { - const sourceObject = source; - if (ns.isListSchema() && Array.isArray(sourceObject)) { - const sparse = !!ns.getMergedTraits().sparse; - const newArray = []; - let i = 0; - for (const item of sourceObject) { - const value = this.serialize(ns.getValueSchema(), item); - if (value != null || sparse) { - newArray[i++] = value; - } - } - return newArray; - } - if (sourceObject instanceof Date) { - return dateToTag(sourceObject); - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - for (const key of Object.keys(sourceObject)) { - const value = this.serialize(ns.getValueSchema(), sourceObject[key]); - if (value != null || sparse) { - newObject[key] = value; - } - } - } else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - const value = this.serialize(memberSchema, sourceObject[key]); - if (value != null) { - newObject[key] = value; - } - } - } else if (ns.isDocumentSchema()) { - for (const key of Object.keys(sourceObject)) { - newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); } } - return newObject; } - return source; - } - flush() { - const buffer = cbor.serialize(this.value); - this.value = void 0; - return buffer; - } -}; -var CborShapeDeserializer = class { - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(schema, bytes) { - const data2 = cbor.deserialize(bytes); - return this.readValue(schema, data2); + return socketWarningTimestamp; } - /** - * Public because it's called by the protocol implementation to deserialize errors. - * @internal - */ - readValue(_schema, value) { - const ns = import_schema.NormalizedSchema.of(_schema); - if (ns.isTimestampSchema() && typeof value === "number") { - return (0, import_serde3.parseEpochTimestamp)(value); + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; } - if (ns.isBlobSchema()) { - if (typeof value === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(value); + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); } - return value; - } - if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") { - return value; - } else if (typeof value === "function" || typeof value === "object") { - if (value === null) { - return null; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; } - if ("byteLength" in value) { - return value; + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; } - if (value instanceof Date) { - return value; + let path = request.path; + if (queryString) { + path += `?${queryString}`; } - if (ns.isDocumentSchema()) { - return value; + if (request.fragment) { + path += `#${request.fragment}`; } - if (ns.isListSchema()) { - const newArray = []; - const memberSchema = ns.getValueSchema(); - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - const itemValue = this.readValue(memberSchema, item); - if (itemValue != null || sparse) { - newArray.push(itemValue); - } - } - return newArray; + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const targetSchema = ns.getValueSchema(); - for (const key of Object.keys(value)) { - const itemValue = this.readValue(targetSchema, value[key]); - if (itemValue != null || sparse) { - newObject[key] = itemValue; - } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); } - } else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - newObject[key] = this.readValue(memberSchema, value[key]); + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; } } - return newObject; - } else { - return value; - } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; } }; -// src/submodules/cbor/SmithyRpcV2CborProtocol.ts -var SmithyRpcV2CborProtocol = class extends import_protocols2.RpcProtocol { - constructor({ defaultNamespace }) { - super({ defaultNamespace }); - this.codec = new CborCodec(); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); +// src/node-http2-handler.ts + + +var import_http22 = __nccwpck_require__(85675); + +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); + +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; } - getShapeId() { - return "smithy.protocols#rpcv2Cbor"; + static { + __name(this, "NodeHttp2ConnectionPool"); } - getPayloadCodec() { - return this.codec; + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - Object.assign(request.headers, { - "content-type": this.getDefaultContentType(), - "smithy-protocol": "rpc-v2-cbor", - accept: this.getDefaultContentType() - }); - if ((0, import_schema2.deref)(operationSchema.input) === "unit") { - delete request.body; - delete request.headers["content-type"]; - } else { - if (!request.body) { - this.serializer.write(15, {}); - request.body = this.serializer.flush(); - } - try { - request.headers["content-length"] = String(request.body.byteLength); - } catch (e) { + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } } } - const { service, operation } = (0, import_util_middleware.getSmithyContext)(context); - const path = `/service/${service}/operation/${operation}`; - if (request.path.endsWith("/")) { - request.path += path.slice(1); - } else { - request.path += path; + } +}; + +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); } - return request; } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); + static { + __name(this, "NodeHttp2ConnectionManager"); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - if (errorName.includes("#")) { - [namespace] = errorName.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $response: response, - $fault: response.statusCode <= 500 ? "client" : "server" - }; - const registry = import_schema2.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorName); - } catch (e) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; - } - const baseExceptionSchema = import_schema2.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); } - const ns = import_schema2.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); } - throw Object.assign( - exception, - errorMetadata, - { - $fault: ns.getMergedTraits().error, - message - }, - output - ); - } - getDefaultContentType() { - return "application/cbor"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 13333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/event-streams/index.ts -var index_exports = {}; -__export(index_exports, { - EventStreamSerde: () => EventStreamSerde -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/event-streams/EventStreamSerde.ts -var import_schema = __nccwpck_require__(79724); -var import_util_utf8 = __nccwpck_require__(60791); -var EventStreamSerde = class { /** - * Properties are injected by the HttpProtocol. + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. */ - constructor({ - marshaller, - serializer, - deserializer, - serdeContext, - defaultContentType - }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; - } - for await (const page of eventStream) { - yield page; + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); } + connectionPool.remove(session); } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( - unionMember, - unionSchema, - event - ); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); + this.sessionCache.delete(key); + } } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream for the end-user. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) - }; + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +}; + +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); } else { - return { - $unknown: event - }; + resolve(options || {}); } }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; + } + static { + __name(this, "NodeHttp2Handler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error( - "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." - ); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; + return new _NodeHttp2Handler(instanceOrOptions); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; } - }; - } - /** - * @param unionMember - member name within the structure that contains an event stream union. - * @param unionSchema - schema of the union. - * @param event - * - * @returns the event body (bytes) and event type (string). - */ - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = unionSchema.hasMemberSchema(unionMember); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(import_schema.SCHEMA.DOCUMENT, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; - } - } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { - serializer.write(eventSchema, event[unionMember]); + abortSignal.onabort = onAbort; } - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; } }; + +// src/stream-collector/collector.ts + +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + static { + __name(this, "Collector"); + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +}; + +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 97332: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 74558: +/***/ ((module) => { -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -50849,911 +38333,617 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(99542); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; - -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(79724); -var import_serde = __nccwpck_require__(99628); -var import_protocol_http2 = __nccwpck_require__(17898); -var import_util_stream2 = __nccwpck_require__(99542); - -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(79724); -var import_protocol_http = __nccwpck_require__(17898); -var HttpProtocol = class { - constructor(options) { - this.options = options; - } - getRequestType() { - return import_protocol_http.HttpRequest; - } - getResponseType() { - return import_protocol_http.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; - } - } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); + static { + __name(this, "ProviderError"); } /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }); + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } +}; + +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { /** - * Loads eventStream capability async (for chunking). + * @override */ - async loadEventStreamCapability() { - const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(13333))); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + static { + __name(this, "CredentialsProviderError"); } +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { /** - * @returns content-type default header value for event stream events and other documents. + * @override */ - getDefaultContentType() { - throw new Error( - `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` - ); - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - void schema; - void context; - void response; - void arg4; - void arg5; - return []; + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); - } - return context.eventStreamMarshaller; + static { + __name(this, "TokenProviderError"); } }; -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } - } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); - } - } else { - payload = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; - } - } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); - } - } - return; - } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); - } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); + throw err; } } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; - } - } + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - valueSchema, - value - ); - } - } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); } - } - return nonHttpBindingMembers; - } -}; - -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(79724); -var import_protocol_http3 = __nccwpck_require__(17898); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input + return resolved; }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); - } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest - }); - } - } else { - serializer.write(schema, _input); - payload = serializer.flush(); - } - } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; + if (isConstant) { + return resolved; } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject - }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 46572: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(17898); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = __nccwpck_require__(42394); +var Field = class { + static { + __name(this, "Field"); } - return resolvedPath2; -}; - -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); - } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); } /** - * Brevity setter for "hostname". + * Overwrite existing field values. + * + * @param values The new field values. */ - hn(hostname) { - this.hostname = hostname; - return this; + set(values) { + this.values = values; } /** - * Brevity initial builder for "basepath". + * Remove all matching entries from list. + * + * @param value Value to remove. */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; + remove(value) { + this.values = this.values.filter((v) => v !== value); } /** - * Brevity incremental builder for "path". + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); } /** - * Brevity setter for "headers". + * Get string values as a list + * + * @returns Values in {@link Field} as a list. */ - h(headers) { - this.headers = headers; - return this; + get() { + return this.values; + } +}; + +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); } /** - * Brevity setter for "query". + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. */ - q(query) { - this.query = query; - return this; + setField(field) { + this.entries[field.name.toLowerCase()] = field; } /** - * Brevity setter for "body". + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. */ - b(body) { - this.body = body; - return this; + getField(name) { + return this.entries[name.toLowerCase()]; } /** - * Brevity setter for "method". + * Delete entry from collection. + * + * @param name Name of the entry to delete. */ - m(method) { - this.method = method; - return this; + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); } }; -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(79724); -var import_serde2 = __nccwpck_require__(99628); -var import_util_base64 = __nccwpck_require__(96039); -var import_util_utf8 = __nccwpck_require__(60791); - -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(79724); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} +// src/httpRequest.ts -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; + return cloned; + } + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; } - return data; + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); } }; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(79724); -var import_util_utf82 = __nccwpck_require__(60791); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; - } - } - return this.codecDeserializer.read(ns, data); + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(79724); +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(79724); -var import_serde3 = __nccwpck_require__(99628); -var import_util_base642 = __nccwpck_require__(96039); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; +0 && (0); + + + +/***/ }), + +/***/ 36600: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( - true - )}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(index_exports); +var import_util_uri_escape = __nccwpck_require__(54474); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); } } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 83966: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + parseQueryString: () => parseQueryString +}); +module.exports = __toCommonJS(index_exports); +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } + } } -}; + return query; +} +__name(parseQueryString, "parseQueryString"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; +0 && (0); + + + +/***/ }), + +/***/ 59652: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; + + +/***/ }), + +/***/ 17621: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(59652); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 81910: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(17621); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; } - return this.codecSerializer.flush(); - } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 79724: +/***/ 56700: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -51766,1471 +38956,1483 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(59652), module.exports); -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(17621), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(81910); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(42394); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - return schemaRef; -}; + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } + } +), "getConfigData"); -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(17898); -var import_util_middleware = __nccwpck_require__(56182); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, - { - ...config, - ...context - }, - response - ); - return { - response, - output: parsed - }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(59652); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); + +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(59652); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(59652); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); } + } else { + currentSection = sectionName; } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; } - } catch (e) { } } - throw error2; } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; - -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(56182); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; + return map; +}, "parseIni"); -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSchemaSerdePlugin(config) { +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(89198); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - } + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] }; -} +}, "loadSharedConfigFiles"); -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - } - static { - this.registries = /* @__PURE__ */ new Map(); - } - /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. - */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. - */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); - } - /** - * @param shapeId - query. - * @returns the schema. - */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. - */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(89198); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; } } - return void 0; - } - /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. - */ - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - /** - * Unloads the current TypeRegistry. - */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(81910); +var import_slurpFile3 = __nccwpck_require__(89198); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; } }; +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - static assign(instance, values) { - const schema = Object.assign(instance, values); - TypeRegistry.for(schema.namespace).register(schema.name, schema); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; +0 && (0); + + + +/***/ }), + +/***/ 89198: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; }; +exports.slurpFile = slurpFile; -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/lis"); - } -}; -var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema -}); -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/map"); - } -}; -var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema -}); +/***/ }), -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class _OperationSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _OperationSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/ope"); - } -}; -var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output -}); +/***/ 42394: +/***/ ((module) => { -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _StructureSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/str"); - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList -}); - -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor() { - super(...arguments); - this.symbol = _ErrorSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/err"); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); +module.exports = __toCommonJS(index_exports); -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 -}; +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _SimpleSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/sim"); - } -}; -var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef -}); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { - /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. - */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; - } - if (schema instanceof _NormalizedSchema) { - Object.assign(this, schema); - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; - } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; - } - this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); - } - } - static { - this.symbol = Symbol.for("@smithy/nor"); +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - static [Symbol.hasInstance](lhs) { - return Schema[Symbol.hasInstance].bind(this)(lhs); + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref) { - if (ref instanceof _NormalizedSchema) { - return ref; - } - if (Array.isArray(ref)) { - const [ns, traits] = ref; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); - return ns; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - return new _NormalizedSchema(ref); + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 38006: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; - } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i++ & 1) === 1) { - traits[trait] = 1; - } - } - return traits; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + parseUrl: () => parseUrl +}); +module.exports = __toCommonJS(index_exports); +var import_querystring_parser = __nccwpck_require__(83966); +var parseUrl = /* @__PURE__ */ __name((url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - Object.assign(this, { schema: this.schema.getSchema() }); - return this.schema; - } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); - } - return deref(this.schema); + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = (0, import_querystring_parser.parseQueryString)(search); } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; - } + return { + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query + }; +}, "parseUrl"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 38330: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(54351); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; + + +/***/ }), + +/***/ 76249: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(38330), module.exports); +__reExport(index_exports, __nccwpck_require__(97055), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 97055: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(54351); +const util_utf8_1 = __nccwpck_require__(55969); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); } - return inner instanceof ListSchema; - } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + else { + input = _input; } - return inner instanceof MapSchema; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; - } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; + + +/***/ }), + +/***/ 54351: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(index_exports); +var import_is_array_buffer = __nccwpck_require__(56186); +var import_buffer = __nccwpck_require__(20181); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 61307: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(index_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; - } - return this.getSchema() === SCHEMA.STREAMING_BLOB; + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } - return false; - } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() - }); } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 26252: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); - } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); - } - const schema = this.getSchema(); - if (typeof schema === "number") { - return this.memberFrom([63 & schema, 0], "key"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider +}); +module.exports = __toCommonJS(index_exports); + +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(42394); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 47324: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; } - return this.memberFrom([schema.keySchema, 0], "key"); - } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return this.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([63 & schema, 0], "member"); - } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); - } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return this.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([collection.valueSchema, 0], "member"); + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; } - } - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); - } - /** - * @param member - to query. - * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). - */ - hasMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - return struct2.memberNames.includes(member); - } - return false; - } - /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. - */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!struct2.memberNames.includes(member)) { - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); - } - const i = struct2.memberNames.indexOf(member); - const memberSchema = struct2.memberList[i]; - return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], member); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); - } - /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @deprecated use (checked) structIterator instead. - * - * @returns a map of member names to member schemas (normalized). - */ - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; - } - } catch (ignored) { - } - return buffer; - } - /** - * @returns member name of event stream or empty string indicating none exists or this - * isn't a structure schema. - */ - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; } - } - } - return ""; - } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; + this.reset(); + return aggregation; } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + reset() { + this.byteArrays = []; + this.byteLength = 0; } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; +} +exports.ByteArrayCollector = ByteArrayCollector; + + +/***/ }), + +/***/ 75233: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 97975: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(76249); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); } - } - /** - * Creates a normalized member schema from the given schema and member name. - */ - memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); } - return new _NormalizedSchema(memberSchema, memberName); - } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); } - return "Unknown"; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +} +exports.ChecksumStream = ChecksumStream; /***/ }), -/***/ 99628: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 58473: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(76249); +const stream_type_check_1 = __nccwpck_require__(17782); +const ChecksumStream_browser_1 = __nccwpck_require__(75233); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +exports.createChecksumStream = createChecksumStream; -// src/submodules/serde/index.ts -var index_exports = {}; -__export(index_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort -}); -module.exports = __toCommonJS(index_exports); -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; +/***/ }), -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; +/***/ 53535: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(17782); +const ChecksumStream_1 = __nccwpck_require__(97975); +const createChecksumStream_browser_1 = __nccwpck_require__(58473); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; + return new ChecksumStream_1.ChecksumStream(init); +} + + +/***/ }), + +/***/ 76861: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(47324); +const createBufferedReadableStream_1 = __nccwpck_require__(74381); +const stream_type_check_1 = __nccwpck_require__(17782); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} + + +/***/ }), + +/***/ 74381: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(47324); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -var parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}; -var logger = { - warn: console.warn + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} + + +/***/ }), + +/***/ 42098: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; }; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; + +/***/ }), + +/***/ 39562: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; } -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}; -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); + + +/***/ }), + +/***/ 53188: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(39562); +const stream_type_check_1 = __nccwpck_require__(17782); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); }; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} + + +/***/ }), + +/***/ 64356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return input; + return to; }; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +}); +module.exports = __toCommonJS(index_exports); + +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(76249); +var import_util_utf8 = __nccwpck_require__(55969); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); } - return monthIdx + 1; -}; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static { + __name(this, "Uint8ArrayBlobAdapter"); } -}; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + /** + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + */ + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; + /** + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. + */ + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; } - return strictParseFloat32("0." + value) * 1e3; -}; -var parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + /** + * @param encoding - default 'utf-8'. + * @returns the blob as string. + */ + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; }; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(97975), module.exports); +__reExport(index_exports, __nccwpck_require__(53535), module.exports); +__reExport(index_exports, __nccwpck_require__(76861), module.exports); +__reExport(index_exports, __nccwpck_require__(42098), module.exports); +__reExport(index_exports, __nccwpck_require__(53188), module.exports); +__reExport(index_exports, __nccwpck_require__(23657), module.exports); +__reExport(index_exports, __nccwpck_require__(60964), module.exports); +__reExport(index_exports, __nccwpck_require__(17782), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 9655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(90793); +const util_base64_1 = __nccwpck_require__(76249); +const util_hex_encoding_1 = __nccwpck_require__(61307); +const util_utf8_1 = __nccwpck_require__(55969); +const stream_type_check_1 = __nccwpck_require__(17782); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); }; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(12048); -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - } - }); - return str; -}; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); - } - return LazyJsonString(JSON.stringify(object)); -}; -LazyJsonString.fromObject = LazyJsonString.from; +/***/ }), -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} +/***/ 23657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/submodules/serde/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; -} +"use strict"; -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(60967); +const util_buffer_from_1 = __nccwpck_require__(54351); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(9655); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } - break; - default: - } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); - } - return v.replace(/\\"/g, '"'); - }); + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); }; +exports.sdkStreamMixin = sdkStreamMixin; -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); - } - dot = 1; - continue; - } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); - } - } - } - toString() { - return this.string; - } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; - } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); - if (prototypeMatch) { - return prototypeMatch; + +/***/ }), + +/***/ 36874: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { - return true; + const readableStream = stream; + return readableStream.tee(); +} + + +/***/ }), + +/***/ 60964: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(36874); +const stream_type_check_1 = __nccwpck_require__(17782); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); } - return prototypeMatch; - } -}; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; } -// Annotate the CommonJS export names for ESM import in node: -0 && (0); /***/ }), -/***/ 83879: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 17782: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +}; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; + + +/***/ }), + +/***/ 54474: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -53254,240 +40456,88 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath }); module.exports = __toCommonJS(index_exports); -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(17898); -var import_querystring_builder = __nccwpck_require__(31622); +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); +0 && (0); -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 + + +/***/ }), + +/***/ 55969: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(96039); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(index_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(54351); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -53496,9 +40546,25 @@ __name(readToBase64, "readToBase64"); /***/ }), -/***/ 77544: +/***/ 8704: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(61860); +tslib_1.__exportStar(__nccwpck_require__(5152), exports); +tslib_1.__exportStar(__nccwpck_require__(97523), exports); +tslib_1.__exportStar(__nccwpck_require__(37288), exports); + + +/***/ }), + +/***/ 5152: /***/ ((module) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -53518,24 +40584,79 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/client/index.ts var index_exports = {}; __export(index_exports, { - isArrayBuffer: () => isArrayBuffer + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + setCredentialFeature: () => setCredentialFeature, + setFeature: () => setFeature, + setTokenFeature: () => setTokenFeature, + state: () => state }); module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +// src/submodules/client/emitWarningIfUnsupportedVersion.ts +var state = { + warningEmitted: false +}; +var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning( + `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/74kJMmI` + ); + } +}, "emitWarningIfUnsupportedVersion"); +// src/submodules/client/setCredentialFeature.ts +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} +__name(setCredentialFeature, "setCredentialFeature"); + +// src/submodules/client/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {} + }; + } else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} +__name(setFeature, "setFeature"); + +// src/submodules/client/setTokenFeature.ts +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} +__name(setTokenFeature, "setTokenFeature"); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 88037: +/***/ 97523: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -53555,122 +40676,378 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/httpAuthSchemes/index.ts var index_exports = {}; __export(index_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption + AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, + AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, + AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, + NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, + NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, + getBearerTokenEnvKey: () => getBearerTokenEnvKey, + resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, + resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, + resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, + validateSigningProperties: () => validateSigningProperties }); module.exports = __toCommonJS(index_exports); -// src/deserializerMiddleware.ts +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts +var import_protocol_http2 = __nccwpck_require__(17898); + +// src/submodules/httpAuthSchemes/utils/getDateHeader.ts var import_protocol_http = __nccwpck_require__(17898); -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } +var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); + +// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts +var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); + +// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts +var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); + +// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts +var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; +}, "getUpdatedSystemClockOffset"); + +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts +var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}, "throwSigningPropertyError"); +var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { + const context = throwSigningPropertyError( + "context", + signingProperties.context + ); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError( + "signer", + config.signer + ); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName + }; +}, "validateSigningProperties"); +var AwsSdkSigV4Signer = class { + static { + __name(this, "AwsSdkSigV4Signer"); + } + async sign(httpRequest, identity, signingProperties) { + if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion, + signingService: signingName + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; } - } catch (e) { } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); } - throw error; } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); +}; +var AWSSDKSigV4Signer = AwsSdkSigV4Signer; -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts +var import_protocol_http3 = __nccwpck_require__(17898); +var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { + static { + __name(this, "AwsSdkSigV4ASigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( + signingProperties + ); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName + }); + return signedRequest; + } +}; + +// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts +var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); + +// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts +var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); + +// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts +var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + /** + * Retrieves auth scheme preference from environment variables + * @param env - Node process environment object + * @returns Array of auth scheme strings if preference is set, undefined otherwise + */ + environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, "environmentVariableSelector"), + /** + * Retrieves auth scheme preference from config file + * @param profile - Config profile object + * @returns Array of auth scheme strings if preference is set, undefined otherwise + */ + configFileSelector: /* @__PURE__ */ __name((profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, "configFileSelector"), + /** + * Default auth scheme preference if not specified in environment or config + */ + default: [] +}; + +// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts +var import_core = __nccwpck_require__(88180); +var import_property_provider = __nccwpck_require__(6180); +var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { + config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); + return config; +}, "resolveAwsSdkSigV4AConfig"); +var NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true + }); + }, + default: void 0 +}; + +// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts +var import_client = __nccwpck_require__(5152); +var import_core2 = __nccwpck_require__(88180); +var import_signature_v4 = __nccwpck_require__(75118); +var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = void 0; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( + (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") + ), "resolvedCredentials"); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true + }); + config.credentials = inputCredentials; + const { + // Default for signingEscapePath + signingEscapePath = true, + // Default for systemClockOffset + systemClockOffset = config.systemClockOffset || 0, + // No default for sha256 since it is platform dependent + sha256 + } = config; + let signer; + if (config.signer) { + signer = (0, import_core2.normalizeProvider)(config.signer); + } else if (config.regionInfoProvider) { + signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( + async (region) => [ + await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint() + }) || {}, + region + ] + ).then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }), "signer"); + } else { + signer = /* @__PURE__ */ __name(async (authScheme) => { + authScheme = Object.assign( + {}, + { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), + properties: {} + }, + authScheme + ); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }, "signer"); + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer + }); + return resolvedConfig; +}, "resolveAwsSdkSigV4Config"); +var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { + credentials, + credentialDefaultProvider +}) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); + } else { + credentialsProvider = credentials; + } + } else { + if (credentialDefaultProvider) { + credentialsProvider = (0, import_core2.normalizeProvider)( + credentialDefaultProvider( + Object.assign({}, config, { + parentClientConfig: config + }) + ) + ); + } else { + credentialsProvider = /* @__PURE__ */ __name(async () => { + throw new Error( + "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." + ); + }, "credentialsProvider"); + } } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); - -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: /* @__PURE__ */ __name((commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, "applyToStack") - }; + credentialsProvider.memoized = true; + return credentialsProvider; } -__name(getSerdePlugin, "getSerdePlugin"); +__name(normalizeCredentialProvider, "normalizeCredentialProvider"); +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} +__name(bindCallerConfig, "bindCallerConfig"); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 39417: +/***/ 37288: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __create = Object.create; +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -53685,1685 +41062,1913 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/protocols/index.ts var index_exports = {}; __export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector + AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, + AwsJson1_0Protocol: () => AwsJson1_0Protocol, + AwsJson1_1Protocol: () => AwsJson1_1Protocol, + AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, + AwsQueryProtocol: () => AwsQueryProtocol, + AwsRestJsonProtocol: () => AwsRestJsonProtocol, + AwsRestXmlProtocol: () => AwsRestXmlProtocol, + AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol, + JsonCodec: () => JsonCodec, + JsonShapeDeserializer: () => JsonShapeDeserializer, + JsonShapeSerializer: () => JsonShapeSerializer, + XmlCodec: () => XmlCodec, + XmlShapeDeserializer: () => XmlShapeDeserializer, + XmlShapeSerializer: () => XmlShapeSerializer, + _toBool: () => _toBool, + _toNum: () => _toNum, + _toStr: () => _toStr, + awsExpectUnion: () => awsExpectUnion, + loadRestJsonErrorCode: () => loadRestJsonErrorCode, + loadRestXmlErrorCode: () => loadRestXmlErrorCode, + parseJsonBody: () => parseJsonBody, + parseJsonErrorBody: () => parseJsonErrorBody, + parseXmlBody: () => parseXmlBody, + parseXmlErrorBody: () => parseXmlErrorBody }); module.exports = __toCommonJS(index_exports); -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(17898); -var import_querystring_builder = __nccwpck_require__(31622); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") -}; - -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} -__name(writeBody, "writeBody"); +// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts +var import_cbor = __nccwpck_require__(20695); +var import_schema2 = __nccwpck_require__(79724); -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } +// src/submodules/protocols/ProtocolLib.ts +var import_schema = __nccwpck_require__(79724); +var import_util_body_length_browser = __nccwpck_require__(24192); +var ProtocolLib = class { static { - __name(this, "NodeHttpHandler"); + __name(this, "ProtocolLib"); } /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * @param body - to be inspected. + * @param serdeContext - this is a subset type but in practice is the client.config having a property called bodyLengthChecker. + * + * @returns content-length value for the body if possible. + * @throws Error and should be caught and handled if not possible to determine length. */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); + calculateContentLength(body, serdeContext) { + const bodyLengthCalculator = serdeContext?.bodyLengthChecker ?? import_util_body_length_browser.calculateBodyLength; + return String(bodyLengthCalculator(body)); } /** - * @internal + * This is only for REST protocols. * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. + * @param defaultContentType - of the protocol. + * @param inputSchema - schema for which to determine content type. + * + * @returns content-type header value or undefined when not applicable. */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; } else { - hostname = request.hostname; + return defaultContentType; } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } + } else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } + if (hasBody) { + return defaultContentType; } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); + } + } + /** + * Shared code for finding error schema or throwing an unmodeled base error. + * @returns error schema and error metadata. + * + * @throws ServiceBaseException or generic Error if no error schema could be found. + */ + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let namespace = defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $response: response, + $fault: response.statusCode < 500 ? "client" : "server" + }; + const registry = import_schema.TypeRegistry.for(namespace); + try { + const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } catch (e) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); + const baseExceptionSchema = import_schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = baseExceptionSchema.ctor; + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value + /** + * Reads the x-amzn-query-error header for awsQuery compatibility. + * + * @param output - values that will be assigned to an error object. + * @param response - from which to read awsQueryError headers. + */ + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== void 0 && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const entries = Object.entries(output); + const Error2 = { + Code, + Type }; - }); + Object.assign(output, Error2); + for (const [k, v] of entries) { + Error2[k] = v; + } + delete Error2.__type; + output.Error = Error2; + } } - httpHandlerConfigs() { - return this.config ?? {}; + /** + * Assigns Error, Type, Code from the awsQuery error object to the output error object. + * @param queryCompatErrorData - query compat error object. + * @param errorData - canonical error object returned to the caller. + */ + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } } }; -// src/node-http2-handler.ts - - -var import_http22 = __nccwpck_require__(85675); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); +// src/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.ts +var AwsSmithyRpcV2CborProtocol = class extends import_cbor.SmithyRpcV2CborProtocol { + static { + __name(this, "AwsSmithyRpcV2CborProtocol"); + } + awsQueryCompatible; + mixin = new ProtocolLib(); + constructor({ + defaultNamespace, + awsQueryCompatible + }) { + super({ defaultNamespace }); + this.awsQueryCompatible = !!awsQueryCompatible; + } + /** + * @override + */ + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + /** + * @override + */ + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = (0, import_cbor.loadSmithyRpcV2CborErrorCode)(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( + errorName, + this.options.defaultNamespace, + response, + dataObject, + metadata + ); + const ns = import_schema2.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); + } +}; -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; +// src/submodules/protocols/coercing-serializers.ts +var _toStr = /* @__PURE__ */ __name((val) => { + if (val == null) { + return val; } - static { - __name(this, "NodeHttp2ConnectionPool"); + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; +}, "_toStr"); +var _toBool = /* @__PURE__ */ __name((val) => { + if (val == null) { + return val; + } + if (typeof val === "number") { + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); } + return val !== "" && lowercase !== "false"; } - offerLast(session) { - this.sessions.push(session); + return val; +}, "_toBool"); +var _toNum = /* @__PURE__ */ __name((val) => { + if (val == null) { + return val; } - contains(session) { - return this.sessions.includes(session); + if (typeof val === "boolean") { } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); + return val; +}, "_toNum"); + +// src/submodules/protocols/json/AwsJsonRpcProtocol.ts +var import_protocols3 = __nccwpck_require__(97332); +var import_schema5 = __nccwpck_require__(79724); + +// src/submodules/protocols/ConfigurableSerdeContext.ts +var SerdeContextConfig = class { + static { + __name(this, "SerdeContextConfig"); } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +}; + +// src/submodules/protocols/json/JsonShapeDeserializer.ts +var import_protocols = __nccwpck_require__(97332); +var import_schema3 = __nccwpck_require__(79724); +var import_serde2 = __nccwpck_require__(99628); +var import_util_base64 = __nccwpck_require__(96039); + +// src/submodules/protocols/json/jsonReviver.ts +var import_serde = __nccwpck_require__(99628); +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new import_serde.NumericValue(numericString, "bigDecimal"); + } else { + return BigInt(numericString); } } } } -}; + return value; +} +__name(jsonReviver, "jsonReviver"); -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); +// src/submodules/protocols/common.ts +var import_smithy_client = __nccwpck_require__(61411); +var import_util_utf8 = __nccwpck_require__(60791); +var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_util_utf8.toUtf8)(body)), "collectBodyString"); + +// src/submodules/protocols/json/parseJsonBody.ts +var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded + }); + } + throw e; + } + } + return {}; +}), "parseJsonBody"); +var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}, "parseJsonErrorBody"); +var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { + const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); + const sanitizeErrorCode = /* @__PURE__ */ __name((rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }, "sanitizeErrorCode"); + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== void 0) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== void 0) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== void 0) { + return sanitizeErrorCode(data["__type"]); } } +}, "loadRestJsonErrorCode"); + +// src/submodules/protocols/json/JsonShapeDeserializer.ts +var JsonShapeDeserializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + } static { - __name(this, "NodeHttp2ConnectionManager"); + __name(this, "JsonShapeDeserializer"); } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; + async read(schema, data) { + return this._read( + schema, + typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) + ); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = import_schema3.NormalizedSchema.of(schema); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._read(listMember, item)); + } } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); + return out; + } else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._read(mapMember, _v); } - }); + } + return out; + } else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const deserializedValue = this._read(memberSchema, value[fromKey]); + if (deserializedValue != null) { + out[memberName] = deserializedValue; + } + } + return out; } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + if (ns.isBlobSchema() && typeof value === "string") { + return (0, import_util_base64.fromBase64)(value); } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return import_serde2.LazyJsonString.from(value); + } + } + if (ns.isTimestampSchema() && value != null) { + const format = (0, import_protocols.determineTimestampFormat)(ns, this.settings); + switch (format) { + case import_schema3.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); + case import_schema3.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(value); + case import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != void 0) { + if (value instanceof import_serde2.NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new import_serde2.NumericValue(untyped.string, untyped.type); + } + return new import_serde2.NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof import_serde2.NumericValue) { + out[k] = v; + } else { + out[k] = this._read(ns, v); + } + } + return out; + } else { + return structuredClone(value); + } + } + return value; + } +}; + +// src/submodules/protocols/json/JsonShapeSerializer.ts +var import_protocols2 = __nccwpck_require__(97332); +var import_schema4 = __nccwpck_require__(79724); +var import_serde4 = __nccwpck_require__(99628); +var import_util_base642 = __nccwpck_require__(96039); + +// src/submodules/protocols/json/jsonReplacer.ts +var import_serde3 = __nccwpck_require__(99628); +var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +var JsonReplacer = class { + static { + __name(this, "JsonReplacer"); } /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. + * Stores placeholder key to true serialized value lookup. */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; + values = /* @__PURE__ */ new Map(); + counter = 0; + stage = 0; + /** + * Creates a jsonReplacer function that reserves big integer and big decimal values + * for later replacement. + */ + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); } - if (!existingConnectionPool.contains(session)) { - return; + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); + this.stage = 1; + return (key, value) => { + if (value instanceof import_serde3.NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; } - this.sessionCache.delete(key); - } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + /** + * Replaces placeholder keys with their true values. + */ + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; } }; -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); +// src/submodules/protocols/json/JsonShapeSerializer.ts +var JsonShapeSerializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; } static { - __name(this, "NodeHttp2Handler"); + __name(this, "JsonShapeSerializer"); + } + buffer; + rootSchema; + write(schema, value) { + this.rootSchema = import_schema4.NormalizedSchema.of(schema); + this.buffer = this._write(this.rootSchema, value); } /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * @internal */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; + writeDiscriminatedDocument(schema, value) { + this.write(schema, value); + if (typeof this.buffer === "object") { + this.buffer.__type = import_schema4.NormalizedSchema.of(schema).getName(true); } - return new _NodeHttp2Handler(instanceOrOptions); } - destroy() { - this.connectionManager.destroy(); + flush() { + const { rootSchema } = this; + this.rootSchema = void 0; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + _write(schema, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = import_schema4.NormalizedSchema.of(schema); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const serializableValue = this._write(memberSchema, value[memberName], ns); + if (serializableValue !== void 0) { + out[targetKey] = serializableValue; + } } + return out; } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string") || ns.isDocumentSchema() && value instanceof Uint8Array) { + if (ns === this.rootSchema) { + return value; } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; + if (!this.serdeContext?.base64Encoder) { + return (0, import_util_base642.toBase64)(value); } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; + return this.serdeContext?.base64Encoder(value); + } + if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { + const format = (0, import_protocols2.determineTimestampFormat)(ns, this.settings); + switch (format) { + case import_schema4.SCHEMA.TIMESTAMP_DATE_TIME: + return value.toISOString().replace(".000Z", "Z"); + case import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde4.dateToUtcString)(value); + case import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return value.getTime() / 1e3; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1e3; } - if (request.fragment) { - path += `#${request.fragment}`; + } + if (ns.isNumericSchema() && typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return (0, import_serde4.generateIdempotencyToken)(); } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + const mediaType = ns.getMergedTraits().mediaType; + if (typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return import_serde4.LazyJsonString.from(value); } } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const [k, v] of Object.entries(value)) { + if (v instanceof import_serde4.NumericValue) { + out[k] = v; + } else { + out[k] = this._write(ns, v); + } } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); + return out; + } else { + return structuredClone(value); + } } + return value; } }; -// src/stream-collector/collector.ts - -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; +// src/submodules/protocols/json/JsonCodec.ts +var JsonCodec = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; } static { - __name(this, "Collector"); + __name(this, "JsonCodec"); } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; } }; -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/submodules/protocols/json/AwsJsonRpcProtocol.ts +var AwsJsonRpcProtocol = class extends import_protocols3.RpcProtocol { + static { + __name(this, "AwsJsonRpcProtocol"); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); + serializer; + deserializer; + serviceTarget; + codec; + mixin = new ProtocolLib(); + awsQueryCompatible; + constructor({ + defaultNamespace, + serviceTarget, + awsQueryCompatible + }) { + super({ + defaultNamespace }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); + this.serviceTarget = serviceTarget; + this.codec = new JsonCodec({ + timestampFormat: { + useTrait: true, + default: import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS + }, + jsonName: false }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; } - isDone = done; + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": `${this.serviceTarget}.${import_schema5.NormalizedSchema.of(operationSchema).getName()}` + }); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if ((0, import_schema5.deref)(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + try { + request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); + } catch (e) { + } + return request; } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + getPayloadCodec() { + return this.codec; } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6180: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( + errorIdentifier, + this.options.defaultNamespace, + response, + dataObject, + metadata + ); + const ns = import_schema5.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); +// src/submodules/protocols/json/AwsJson1_0Protocol.ts +var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { + static { + __name(this, "AwsJson1_0Protocol"); + } + constructor({ + defaultNamespace, + serviceTarget, + awsQueryCompatible + }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + /** + * @override + */ + getDefaultContentType() { + return "application/x-amz-json-1.0"; } +}; + +// src/submodules/protocols/json/AwsJson1_1Protocol.ts +var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { static { - __name(this, "ProviderError"); + __name(this, "AwsJson1_1Protocol"); + } + constructor({ + defaultNamespace, + serviceTarget, + awsQueryCompatible + }) { + super({ + defaultNamespace, + serviceTarget, + awsQueryCompatible + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; } /** - * @deprecated use new operator. + * @override */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); + getDefaultContentType() { + return "application/x-amz-json-1.1"; } }; -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { +// src/submodules/protocols/json/AwsRestJsonProtocol.ts +var import_protocols4 = __nccwpck_require__(97332); +var import_schema6 = __nccwpck_require__(79724); +var AwsRestJsonProtocol = class extends import_protocols4.HttpBindingProtocol { + static { + __name(this, "AwsRestJsonProtocol"); + } + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace }) { + super({ + defaultNamespace + }); + const settings = { + timestampFormat: { + useTrait: true, + default: import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS + }, + httpBindings: true, + jsonName: true + }; + this.codec = new JsonCodec(settings); + this.serializer = new import_protocols4.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new import_protocols4.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = import_schema6.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.headers["content-type"] && !request.body) { + request.body = "{}"; + } + if (request.body) { + try { + request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); + } catch (e) { + } + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( + errorIdentifier, + this.options.defaultNamespace, + response, + dataObject, + metadata + ); + const ns = import_schema6.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); + } /** * @override */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); + getDefaultContentType() { + return "application/json"; } }; -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); +// src/submodules/protocols/json/awsExpectUnion.ts +var import_smithy_client2 = __nccwpck_require__(61411); +var awsExpectUnion = /* @__PURE__ */ __name((value) => { + if (value == null) { + return void 0; } - static { - __name(this, "TokenProviderError"); + if (typeof value === "object" && "__type" in value) { + delete value.__type; } -}; + return (0, import_smithy_client2.expectUnion)(value); +}, "awsExpectUnion"); -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); +// src/submodules/protocols/query/AwsQueryProtocol.ts +var import_protocols7 = __nccwpck_require__(97332); +var import_schema9 = __nccwpck_require__(79724); + +// src/submodules/protocols/xml/XmlShapeDeserializer.ts +var import_protocols5 = __nccwpck_require__(97332); +var import_schema7 = __nccwpck_require__(79724); +var import_smithy_client3 = __nccwpck_require__(61411); +var import_util_utf82 = __nccwpck_require__(60791); +var import_fast_xml_parser = __nccwpck_require__(50591); +var XmlShapeDeserializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new import_protocols5.FromStringShapeDeserializer(settings); } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; + static { + __name(this, "XmlShapeDeserializer"); + } + stringDeserializer; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + /** + * @param schema - describing the data. + * @param bytes - serialized data. + * @param key - used by AwsQuery to step one additional depth into the object before reading it. + */ + read(schema, bytes, key) { + const ns = import_schema7.NormalizedSchema.of(schema); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } else { + output[memberName] = this.read(memberSchemas[memberName], bytes); } - throw err; + return output; } + const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema, key ? parsedObject[key] : parsedObject); } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); + readSchema(_schema, value) { + const ns = import_schema7.NormalizedSchema.of(_schema); + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + if (value == null) { + return value; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + if (typeof value === "object") { + const sparse = !!traits.sparse; + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer2 = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + if (v != null || sparse) { + buffer2.push(this.readSchema(listValue, v)); + } + } + return buffer2; } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value2 = entry[valueProperty]; + if (value2 != null || sparse) { + buffer[key] = this.readSchema(memberNs, value2); + } + } + return buffer; + } + if (ns.isStructSchema()) { + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); } - if (isConstant) { - return resolved; + if (ns.isListSchema()) { + return []; } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + const parser = new import_fast_xml_parser.XMLParser({ + attributeNamePrefix: "", + htmlEntities: true, + ignoreAttributes: false, + ignoreDeclaration: true, + parseTagValue: false, + trimValues: false, + tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") + }); + parser.addEntity("#xD", "\r"); + parser.addEntity("#10", "\n"); + let parsedObj; + try { + parsedObj = parser.parse(xml, true); + } catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 17898: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return {}; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); +// src/submodules/protocols/query/QueryShapeSerializer.ts +var import_protocols6 = __nccwpck_require__(97332); +var import_schema8 = __nccwpck_require__(79724); +var import_serde5 = __nccwpck_require__(99628); +var import_smithy_client4 = __nccwpck_require__(61411); +var import_util_base643 = __nccwpck_require__(96039); +var QueryShapeSerializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + } + static { + __name(this, "QueryShapeSerializer"); + } + buffer; + write(schema, value, prefix = "") { + if (this.buffer === void 0) { + this.buffer = ""; + } + const ns = import_schema8.NormalizedSchema.of(schema); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value)); + } + } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue((0, import_serde5.generateIdempotencyToken)()); + } + } else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof import_serde5.NumericValue ? value.string : String(value)); + } + } else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = (0, import_protocols6.determineTimestampFormat)(ns, this.settings); + switch (format) { + case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: + this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); + break; + case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.writeValue(String(value.getTime() / 1e3)); + break; + } + } + } else if (ns.isDocumentSchema()) { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); + } else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const suffix = this.getKey("member", member.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const [k, v] of Object.entries(value)) { + if (v == null) { + continue; + } + const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + } + } + } else if (ns.isUnitSchema()) { + } else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = __nccwpck_require__(34048); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; + flush() { + if (this.buffer === void 0) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + getKey(memberName, xmlName) { + const key = xmlName ?? memberName; + if (this.settings.capitalizeKeys) { + return key[0].toUpperCase() + key.slice(1); + } + return key; } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${(0, import_protocols6.extendedEncodeURIComponent)(key)}=`; } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; + writeValue(value) { + this.buffer += (0, import_protocols6.extendedEncodeURIComponent)(value); } }; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; +// src/submodules/protocols/query/AwsQueryProtocol.ts +var AwsQueryProtocol = class extends import_protocols7.RpcProtocol { + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); } static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + __name(this, "AwsQueryProtocol"); } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); + serializer; + deserializer; + mixin = new ProtocolLib(); + getShapeId() { + return "aws.protocols#awsQuery"; } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-www-form-urlencoded` }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + if ((0, import_schema9.deref)(operationSchema.input) === "unit" || !request.body) { + request.body = ""; } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); - } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } -}; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 31622: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + try { + request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); + } catch (e) { + } + return request; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(13288); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema9.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes2 = await (0, import_protocols7.collectBody)(response.body, context); + if (bytes2.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema9.SCHEMA.DOCUMENT, bytes2)); } - parts.push(qsEntry); + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; + const bytes = await (0, import_protocols7.collectBody)(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject + }; + return output; } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 34048: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); + /** + * EC2 Query overrides this. + */ + useNestedResult() { + return true; } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 73464: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(45217); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + const errorData = this.loadQueryError(dataObject); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( + errorIdentifier, + this.options.defaultNamespace, + response, + errorData, + metadata, + (registry, errorName) => registry.find( + (schema) => import_schema9.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName + ) + ); + const ns = import_schema9.NormalizedSchema.of(errorSchema); + const message = this.loadQueryErrorMessage(dataObject); + const exception = new errorSchema.ctor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); + } + /** + * The variations in the error and error message locations are attributed to + * divergence between AWS Query and EC2 Query behavior. + */ + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== void 0) { + return code; } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + /** + * @override + */ + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } }; -exports.fromBase64 = fromBase64; - - -/***/ }), - -/***/ 96039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/protocols/query/AwsEc2QueryProtocol.ts +var AwsEc2QueryProtocol = class extends AwsQueryProtocol { + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false + }; + Object.assign(this.serializer.settings, ec2Settings); + } + static { + __name(this, "AwsEc2QueryProtocol"); + } + /** + * EC2 Query reads XResponse.XResult instead of XResponse directly. + */ + useNestedResult() { + return false; } - return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(73464), module.exports); -__reExport(index_exports, __nccwpck_require__(71189), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +// src/submodules/protocols/xml/AwsRestXmlProtocol.ts +var import_protocols9 = __nccwpck_require__(97332); +var import_schema11 = __nccwpck_require__(79724); -/***/ }), - -/***/ 71189: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// src/submodules/protocols/xml/parseXmlBody.ts +var import_smithy_client5 = __nccwpck_require__(61411); +var import_fast_xml_parser2 = __nccwpck_require__(50591); +var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + const parser = new import_fast_xml_parser2.XMLParser({ + attributeNamePrefix: "", + htmlEntities: true, + ignoreAttributes: false, + ignoreDeclaration: true, + parseTagValue: false, + trimValues: false, + tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") + }); + parser.addEntity("#xD", "\r"); + parser.addEntity("#10", "\n"); + let parsedObj; + try { + parsedObj = parser.parse(encoded, true); + } catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return (0, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); + } + return {}; +}), "parseXmlBody"); +var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; +}, "parseXmlErrorBody"); +var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { + if (data?.Error?.Code !== void 0) { + return data.Error.Code; + } + if (data?.Code !== void 0) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}, "loadRestXmlErrorCode"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(45217); -const util_utf8_1 = __nccwpck_require__(60791); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); +// src/submodules/protocols/xml/XmlShapeSerializer.ts +var import_xml_builder = __nccwpck_require__(94274); +var import_protocols8 = __nccwpck_require__(97332); +var import_schema10 = __nccwpck_require__(79724); +var import_serde6 = __nccwpck_require__(99628); +var import_smithy_client6 = __nccwpck_require__(61411); +var import_util_base644 = __nccwpck_require__(96039); +var XmlShapeSerializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + } + static { + __name(this, "XmlShapeSerializer"); + } + stringBuffer; + byteBuffer; + buffer; + write(schema, value) { + const ns = import_schema10.NormalizedSchema.of(schema); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } else if (ns.isBlobSchema()) { + this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base644.fromBase64)(value); + } else { + this.buffer = this.writeStruct(ns, value, void 0); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } } - else { - input = _input; + } + flush() { + if (this.byteBuffer !== void 0) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + if (this.stringBuffer !== void 0) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 24192: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(index_exports); - -// src/calculateBodyLength.ts -var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (typeof body === "string") { - if (TEXT_ENCODER) { - return TEXT_ENCODER.encode(body).byteLength; + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); + if (!name || !ns.isStructSchema()) { + throw new Error( + `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( + true + )}.` + ); } - let len = body.length; - for (let i = len - 1; i >= 0; i--) { - const code = body.charCodeAt(i); - if (code > 127 && code <= 2047) len++; - else if (code > 2047 && code <= 65535) len += 2; - if (code >= 56320 && code <= 57343) i--; + const structXmlNode = import_xml_builder.XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute( + memberSchema.getMergedTraits().xmlName ?? memberName, + this.writeSimple(memberSchema, val) + ); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } else { + const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } } - return len; - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 45217: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error( + `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` + ); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = /* @__PURE__ */ __name((container2, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); + } else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container2, xmlns); + } else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container2.addChildNode( + struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") + ); + } else { + const listItemNode = import_xml_builder.XmlNode.of( + flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" + ); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container2.addChildNode(listItemNode); + } + }, "writeItem"); + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } else { + const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error( + `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` + ); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { + const keyNode = import_xml_builder.XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = import_xml_builder.XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }, "addKeyValue"); + if (flat) { + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } else { + let mapNode; + if (!containerIsMap) { + mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const [key, val] of Object.entries(map)) { + if (sparse || val != null) { + const entry = import_xml_builder.XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = import_schema10.NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base644.toBase64)(value); + } else if (ns.isTimestampSchema() && value instanceof Date) { + const format = (0, import_protocols8.determineTimestampFormat)(ns, this.settings); + switch (format) { + case import_schema10.SCHEMA.TIMESTAMP_DATE_TIME: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema10.SCHEMA.TIMESTAMP_HTTP_DATE: + nodeContents = (0, import_smithy_client6.dateToUtcString)(value); + break; + case import_schema10.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + nodeContents = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = (0, import_smithy_client6.dateToUtcString)(value); + break; + } + } else if (ns.isBigDecimalSchema() && value) { + if (value instanceof import_serde6.NumericValue) { + return value.string; + } + return String(value); + } else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error( + "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." + ); + } else { + throw new Error( + `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( + true + )}` + ); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === void 0 && ns.isIdempotencyToken()) { + nodeContents = (0, import_serde6.generateIdempotencyToken)(); + } else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = import_schema10.NormalizedSchema.of(_schema); + const content = new import_xml_builder.XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(77544); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); +// src/submodules/protocols/xml/XmlCodec.ts +var XmlCodec = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + static { + __name(this, "XmlCodec"); } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 96369: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; +// src/submodules/protocols/xml/AwsRestXmlProtocol.ts +var AwsRestXmlProtocol = class extends import_protocols9.HttpBindingProtocol { + static { + __name(this, "AwsRestXmlProtocol"); } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: import_schema11.SCHEMA.TIMESTAMP_DATE_TIME + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace + }; + this.codec = new XmlCodec(settings); + this.serializer = new import_protocols9.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new import_protocols9.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = import_schema11.NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.headers["content-type"] === this.getDefaultContentType()) { + if (typeof request.body === "string") { + request.body = '' + request.body; + } + } + if (request.body) { + try { + request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); + } catch (e) { + } } + return request; } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); } - return out; -} -__name(toHex, "toHex"); + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException( + errorIdentifier, + this.options.defaultNamespace, + response, + dataObject, + metadata + ); + const ns = import_schema11.NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = this.codec.createDeserializer().readSchema(member, value); + } + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); + } + /** + * @override + */ + getDefaultContentType() { + return "application/xml"; + } +}; // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 56182: +/***/ 88180: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -55388,8 +42993,28 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature }); module.exports = __toCommonJS(index_exports); @@ -55397,526 +43022,396 @@ module.exports = __toCommonJS(index_exports); var import_types = __nccwpck_require__(34048); var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 40238: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(56182); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; +// src/middleware-http-auth-scheme/resolveAuthOptions.ts +var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } } - reset() { - this.byteArrays = []; - this.byteLength = 0; + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); } -} -exports.ByteArrayCollector = ByteArrayCollector; - - -/***/ }), - -/***/ 96783: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + } + return preferredAuthOptions; +}, "resolveAuthOptions"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; } -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 65697: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(96039); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + ); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; } -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 49671: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}, "httpAuthSchemeMiddleware"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(96039); -const stream_type_check_1 = __nccwpck_require__(83040); -const ChecksumStream_browser_1 = __nccwpck_require__(96783); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" }; -exports.createChecksumStream = createChecksumStream; - - -/***/ }), - -/***/ 8921: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(83040); -const ChecksumStream_1 = __nccwpck_require__(65697); -const createChecksumStream_browser_1 = __nccwpck_require__(49671); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(88037); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemePlugin"); +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(17898); -/***/ }), +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); -/***/ 42823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" +}; +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + }, "applyToStack") +}), "getHttpSigningPlugin"); -"use strict"; +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(40238); -const createBufferedReadableStream_1 = __nccwpck_require__(80383); -const stream_type_check_1 = __nccwpck_require__(83040); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; + return void 0; + }, "paginateOperation"); } +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; + } + cursor = cursor[step]; + } + return cursor; +}, "get"); +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(97332); -/***/ }), +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +__name(setFeature, "setFeature"); -/***/ 80383: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { + /** + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure + */ + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } + } + static { + __name(this, "DefaultIdentityProviderConfig"); + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +}; -"use strict"; +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(40238); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); + +var HttpApiKeyAuthSigner = class { + static { + __name(this, "HttpApiKeyAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); } - if (chunk instanceof Uint8Array) { - return 1; + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); } - if (typeof chunk === "string") { - return 0; + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); } - return -1; -} - - -/***/ }), - -/***/ 40588: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; + return clonedRequest; + } }; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts -/***/ }), - -/***/ 44168: -/***/ ((__unused_webpack_module, exports) => { +var HttpBearerAuthSigner = class { + static { + __name(this, "HttpBearerAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } +}; -"use strict"; +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { + static { + __name(this, "NoAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - return collected; -} - - -/***/ }), - -/***/ 91390: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(44168); -const stream_type_check_1 = __nccwpck_require__(83040); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); -}; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; + if (isConstant) { + return resolved; } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; } -} + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 99542: +/***/ 20695: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -55929,889 +43424,1057 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/cbor/index.ts var index_exports = {}; __export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter + CborCodec: () => CborCodec, + CborShapeDeserializer: () => CborShapeDeserializer, + CborShapeSerializer: () => CborShapeSerializer, + SmithyRpcV2CborProtocol: () => SmithyRpcV2CborProtocol, + buildHttpRpcRequest: () => buildHttpRpcRequest, + cbor: () => cbor, + checkCborResponse: () => checkCborResponse, + dateToTag: () => dateToTag, + loadSmithyRpcV2CborErrorCode: () => loadSmithyRpcV2CborErrorCode, + parseCborBody: () => parseCborBody, + parseCborErrorBody: () => parseCborErrorBody, + tag: () => tag, + tagSymbol: () => tagSymbol }); module.exports = __toCommonJS(index_exports); -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(96039); +// src/submodules/cbor/cbor-decode.ts +var import_serde = __nccwpck_require__(99628); var import_util_utf8 = __nccwpck_require__(60791); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); + +// src/submodules/cbor/cbor-types.ts +var majorUint64 = 0; +var majorNegativeInt64 = 1; +var majorUnstructuredByteString = 2; +var majorUtf8String = 3; +var majorList = 4; +var majorMap = 5; +var majorTag = 6; +var majorSpecial = 7; +var specialFalse = 20; +var specialTrue = 21; +var specialNull = 22; +var specialUndefined = 23; +var extendedOneByte = 24; +var extendedFloat16 = 25; +var extendedFloat32 = 26; +var extendedFloat64 = 27; +var minorIndefinite = 31; +function alloc(size) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); +} +var tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); +function tag(data2) { + data2[tagSymbol] = true; + return data2; +} + +// src/submodules/cbor/cbor-decode.ts +var USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; +var USE_BUFFER = typeof Buffer !== "undefined"; +var payload = alloc(0); +var dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +var textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; +var _offset = 0; +function setPayload(bytes) { + payload = bytes; + dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } else { + switch (minor) { + case extendedOneByte: + case extendedFloat16: + case extendedFloat32: + case extendedFloat64: + const countLength = minorValueToArgumentLength[minor]; + const countOffset = countLength + 1; + offset = countOffset; + if (to - at < countOffset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + unsignedInt = payload[countIndex]; + } else if (countLength === 2) { + unsignedInt = dataView.getUint16(countIndex); + } else if (countLength === 4) { + unsignedInt = dataView.getUint32(countIndex); + } else { + unsignedInt = dataView.getBigUint64(countIndex); + } + break; + default: + throw new Error(`unexpected minor value ${minor}.`); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt(unsignedInt); + } else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt(negativeInt); + } else { + if (minor === 2 || minor === 3) { + const length = decodeCount(at + offset, to); + let b = BigInt(0); + const start = at + offset + _offset; + for (let i = start; i < start + length; ++i) { + b = b << BigInt(8) | BigInt(payload[i]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b - BigInt(1) : b; + } else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [exponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); + let numericString; + const sign = mantissa < 0 ? "-" : ""; + numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + _offset = offset + _offset; + return (0, import_serde.nv)(numericString); + } else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt(unsignedInt), value }); + } + } + case majorUtf8String: + case majorMap: + case majorList: + case majorUnstructuredByteString: + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } else { + switch (major) { + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + } + } + default: + return decodeSpecial(at, to); } - return (0, import_util_utf8.toUtf8)(payload); } -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); +function bytesToUtf8(bytes, at, to) { + if (USE_BUFFER && bytes.constructor?.name === "Buffer") { + return bytes.toString("utf-8", at, to); } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); + if (textDecoder) { + return textDecoder.decode(bytes.subarray(at, to)); + } + return (0, import_util_utf8.toUtf8)(bytes.subarray(at, to)); } -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { - static { - __name(this, "Uint8ArrayBlobAdapter"); +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); } - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + return num; +} +var minorValueToArgumentLength = { + [extendedOneByte]: 1, + [extendedFloat16]: 2, + [extendedFloat32]: 4, + [extendedFloat64]: 8 +}; +function bytesToFloat16(a, b) { + const sign = a >> 7; + const exponent = (a & 124) >> 2; + const fraction = (a & 3) << 8 | b; + const scalar = sign === 0 ? 1 : -1; + let exponentComponent; + let summation; + if (exponent === 0) { + if (fraction === 0) { + return 0; + } else { + exponentComponent = Math.pow(2, 1 - 15); + summation = 0; + } + } else if (exponent === 31) { + if (fraction === 0) { + return scalar * Infinity; + } else { + return NaN; } + } else { + exponentComponent = Math.pow(2, exponent - 15); + summation = 1; } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; + summation += fraction / 1024; + return scalar * (exponentComponent * summation); +} +function decodeCount(at, to) { + const minor = payload[at] & 31; + if (minor < 24) { + _offset = 1; + return minor; } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); + if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) { + const countLength = minorValueToArgumentLength[minor]; + _offset = countLength + 1; + if (to - at < _offset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + return payload[countIndex]; + } else if (countLength === 2) { + return dataView.getUint16(countIndex); + } else if (countLength === 4) { + return dataView.getUint32(countIndex); + } + return demote(dataView.getBigUint64(countIndex)); } -}; - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(65697), module.exports); -__reExport(index_exports, __nccwpck_require__(8921), module.exports); -__reExport(index_exports, __nccwpck_require__(42823), module.exports); -__reExport(index_exports, __nccwpck_require__(40588), module.exports); -__reExport(index_exports, __nccwpck_require__(91390), module.exports); -__reExport(index_exports, __nccwpck_require__(34367), module.exports); -__reExport(index_exports, __nccwpck_require__(32638), module.exports); -__reExport(index_exports, __nccwpck_require__(83040), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 51113: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(83879); -const util_base64_1 = __nccwpck_require__(96039); -const util_hex_encoding_1 = __nccwpck_require__(96369); -const util_utf8_1 = __nccwpck_require__(60791); -const stream_type_check_1 = __nccwpck_require__(83040); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + throw new Error(`unexpected minor value ${minor}.`); +} +function decodeUtf8String(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`string len ${length} greater than remaining buf len.`); + } + const value = bytesToUtf8(payload, at, at + length); + _offset = offset + length; + return value; +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + const data2 = alloc(vector.length); + data2.set(vector, 0); + _offset = at - base + 2; + return bytesToUtf8(data2, 0, data2.length); } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 34367: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(39417); -const util_buffer_from_1 = __nccwpck_require__(45217); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(51113); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} in indefinite string.`); } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), - -/***/ 13480: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); + } + const value = payload.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + const data2 = alloc(vector.length); + data2.set(vector, 0); + _offset = at - base + 2; + return data2; } - const readableStream = stream; - return readableStream.tee(); + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + if (major !== majorUnstructuredByteString) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); } - - -/***/ }), - -/***/ 32638: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(13480); -const stream_type_check_1 = __nccwpck_require__(83040); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); +function decodeList(at, to) { + const listDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const list = Array(listDataLength); + for (let i = 0; i < listDataLength; ++i) { + const item = decode(at, to); + const itemOffset = _offset; + list[i] = item; + at += itemOffset; + } + _offset = offset + (at - base); + return list; +} +function decodeListIndefinite(at, to) { + at += 1; + const list = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + _offset = at - base + 2; + return list; } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; + const item = decode(at, to); + const n = _offset; + at += n; + list.push(item); + } + throw new Error("expected break marker."); } - - -/***/ }), - -/***/ 83040: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; - - -/***/ }), - -/***/ 13288: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +function decodeMap(at, to) { + const mapDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const map = {}; + for (let i = 0; i < mapDataLength; ++i) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + const major = (payload[at] & 224) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key at index ${at}.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 60791: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + _offset = offset + (at - base); + return map; +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map = {}; + for (; at < to; ) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + if (payload[at] === 255) { + _offset = at - base + 2; + return map; + } + const major = (payload[at] & 224) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map[key] = value; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(index_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(45217); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); + throw new Error("expected break marker."); +} +function decodeSpecial(at, to) { + const minor = payload[at] & 31; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16(payload[at + 1], payload[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView.getFloat64(at + 1); + default: + throw new Error(`unexpected minor value ${minor}.`); } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); +} +function castBigInt(bigInt) { + if (typeof bigInt === "number") { + return bigInt; } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; +// src/submodules/cbor/cbor-encode.ts +var import_serde2 = __nccwpck_require__(99628); +var import_util_utf82 = __nccwpck_require__(60791); +var USE_BUFFER2 = typeof Buffer !== "undefined"; +var initialSize = 2048; +var data = alloc(initialSize); +var dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); +var cursor = 0; +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor; + if (remaining < bytes) { + if (cursor < 16e6) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } else { + resize(data.byteLength + bytes + 16e6); + } } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); +} +function toUint8Array() { + const out = alloc(cursor); + out.set(data.subarray(0, cursor), 0); + cursor = 0; + return out; +} +function resize(size) { + const old = data; + data = alloc(size); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } else { + data.set(old, 0); + } } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 55606: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeHeader(major, value) { + if (value < 24) { + data[cursor++] = major << 5 | value; + } else if (value < 1 << 8) { + data[cursor++] = major << 5 | 24; + data[cursor++] = value; + } else if (value < 1 << 16) { + data[cursor++] = major << 5 | extendedFloat16; + dataView2.setUint16(cursor, value); + cursor += 2; + } else if (value < 2 ** 32) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, value); + cursor += 4; + } else { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); + cursor += 8; + } +} +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + ensureSpace(typeof input === "string" ? input.length * 4 : 64); + if (typeof input === "string") { + if (USE_BUFFER2) { + encodeHeader(majorUtf8String, Buffer.byteLength(input)); + cursor += data.write(input, cursor); + } else { + const bytes = (0, import_util_utf82.fromUtf8)(input); + encodeHeader(majorUtf8String, bytes.byteLength); + data.set(bytes, cursor); + cursor += bytes.byteLength; + } + continue; + } else if (typeof input === "number") { + if (Number.isInteger(input)) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor++] = major << 5 | value; + } else if (value < 256) { + data[cursor++] = major << 5 | 24; + data[cursor++] = value; + } else if (value < 65536) { + data[cursor++] = major << 5 | extendedFloat16; + data[cursor++] = value >> 8; + data[cursor++] = value; + } else if (value < 4294967296) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, value); + cursor += 4; + } else { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, BigInt(value)); + cursor += 8; + } + continue; + } + data[cursor++] = majorSpecial << 5 | extendedFloat64; + dataView2.setFloat64(cursor, input); + cursor += 8; + continue; + } else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + const n = Number(value); + if (n < 24) { + data[cursor++] = major << 5 | n; + } else if (n < 256) { + data[cursor++] = major << 5 | 24; + data[cursor++] = n; + } else if (n < 65536) { + data[cursor++] = major << 5 | extendedFloat16; + data[cursor++] = n >> 8; + data[cursor++] = n & 255; + } else if (n < 4294967296) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, n); + cursor += 4; + } else if (value < BigInt("18446744073709551616")) { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, value); + cursor += 8; + } else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b = value; + let i = 0; + while (bigIntBytes.byteLength - ++i >= 0) { + bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2); + data[cursor++] = nonNegative ? 194 : 195; + if (USE_BUFFER2) { + encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); + } else { + encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); + } + data.set(bigIntBytes, cursor); + cursor += bigIntBytes.byteLength; + } + continue; + } else if (input === null) { + data[cursor++] = majorSpecial << 5 | specialNull; + continue; + } else if (typeof input === "boolean") { + data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse); + continue; + } else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } else if (Array.isArray(input)) { + for (let i = input.length - 1; i >= 0; --i) { + encodeStack.push(input[i]); + } + encodeHeader(majorList, input.length); + continue; + } else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2); + encodeHeader(majorUnstructuredByteString, input.length); + data.set(input, cursor); + cursor += input.byteLength; + continue; + } else if (typeof input === "object") { + if (input instanceof import_serde2.NumericValue) { + const decimalIndex = input.string.indexOf("."); + const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; + const mantissa = BigInt(input.string.replace(".", "")); + data[cursor++] = 196; + encodeStack.push(mantissa); + encodeStack.push(exponent); + encodeHeader(majorList, 2); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader(majorTag, input.tag); + continue; + } else { + throw new Error( + "tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input) + ); + } + } + const keys = Object.keys(input); + for (let i = keys.length - 1; i >= 0; --i) { + const key = keys[i]; + encodeStack.push(input[key]); + encodeStack.push(key); + } + encodeHeader(majorMap, keys.length); + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, - ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, - ENV_EXPIRATION: () => ENV_EXPIRATION, - ENV_KEY: () => ENV_KEY, - ENV_SECRET: () => ENV_SECRET, - ENV_SESSION: () => ENV_SESSION, - fromEnv: () => fromEnv -}); -module.exports = __toCommonJS(index_exports); +} -// src/fromEnv.ts -var import_client = __nccwpck_require__(5152); -var import_property_provider = __nccwpck_require__(29006); -var ENV_KEY = "AWS_ACCESS_KEY_ID"; -var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; -var ENV_SESSION = "AWS_SESSION_TOKEN"; -var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; -var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; -var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; -var fromEnv = /* @__PURE__ */ __name((init) => async () => { - init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...sessionToken && { sessionToken }, - ...expiry && { expiration: new Date(expiry) }, - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; +// src/submodules/cbor/cbor.ts +var cbor = { + deserialize(payload2) { + setPayload(payload2); + return decode(0, payload2.length); + }, + serialize(input) { + try { + encode(input); + return toUint8Array(); + } catch (e) { + toUint8Array(); + throw e; + } + }, + /** + * @public + * @param size - byte length to allocate. + * + * This may be used to garbage collect the CBOR + * shared encoding buffer space, + * e.g. resizeEncodingBuffer(0); + * + * This may also be used to pre-allocate more space for + * CBOR encoding, e.g. resizeEncodingBuffer(100_000_000); + */ + resizeEncodingBuffer(size) { + resize(size); } - throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); -}, "fromEnv"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 29006: -/***/ ((module) => { +}; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +// src/submodules/cbor/parseCborBody.ts +var import_protocols = __nccwpck_require__(97332); +var import_protocol_http = __nccwpck_require__(17898); +var import_util_body_length_browser = __nccwpck_require__(24192); +var parseCborBody = (streamBody, context) => { + return (0, import_protocols.collectBody)(streamBody, context).then(async (bytes) => { + if (bytes.length) { + try { + return cbor.deserialize(bytes); + } catch (e) { + Object.defineProperty(e, "$responseBodyText", { + value: context.utf8Encoder(bytes) + }); + throw e; + } + } + return {}; + }); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +var dateToTag = (date) => { + return tag({ + tag: 1, + value: date.getTime() / 1e3 + }); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); - -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; +var parseCborErrorBody = async (errorBody, context) => { + const value = await parseCborBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +var loadSmithyRpcV2CborErrorCode = (output, data2) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + if (data2["__type"] !== void 0) { + return sanitizeErrorCode(data2["__type"]); } - static { - __name(this, "ProviderError"); + const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code"); + if (codeKey && data2[codeKey] !== void 0) { + return sanitizeErrorCode(data2[codeKey]); } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); +}; +var checkCborResponse = (response) => { + if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { + throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); } }; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); +var buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers: { + // intentional copy. + ...headers + } + }; + if (resolvedHostname !== void 0) { + contents.hostname = resolvedHostname; } - static { - __name(this, "CredentialsProviderError"); + if (body !== void 0) { + contents.body = body; + try { + contents.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(body)); + } catch (e) { + } } + return new import_protocol_http.HttpRequest(contents); }; -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); +// src/submodules/cbor/SmithyRpcV2CborProtocol.ts +var import_protocols2 = __nccwpck_require__(97332); +var import_schema2 = __nccwpck_require__(79724); +var import_util_middleware = __nccwpck_require__(56182); + +// src/submodules/cbor/CborCodec.ts +var import_schema = __nccwpck_require__(79724); +var import_serde3 = __nccwpck_require__(99628); +var import_util_base64 = __nccwpck_require__(96039); +var CborCodec = class { + createSerializer() { + const serializer = new CborShapeSerializer(); + serializer.setSerdeContext(this.serdeContext); + return serializer; } - static { - __name(this, "TokenProviderError"); + createDeserializer() { + const deserializer = new CborShapeDeserializer(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } }; - -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); +var CborShapeSerializer = class { + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } + write(schema, value) { + this.value = this.serialize(schema, value); } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + /** + * Recursive serializer transform that copies and prepares the user input object + * for CBOR serialization. + */ + serialize(schema, source) { + const ns = import_schema.NormalizedSchema.of(schema); + if (source == null) { + if (ns.isIdempotencyToken()) { + return (0, import_serde3.generateIdempotencyToken)(); } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + return source; } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1509: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkUrl = void 0; -const property_provider_1 = __nccwpck_require__(56855); -const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; -const LOOPBACK_CIDR_IPv6 = "::1/128"; -const ECS_CONTAINER_HOST = "169.254.170.2"; -const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; -const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; -const checkUrl = (url, logger) => { - if (url.protocol === "https:") { - return; + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(source); + } + return source; } - if (url.hostname === ECS_CONTAINER_HOST || - url.hostname === EKS_CONTAINER_HOST_IPv4 || - url.hostname === EKS_CONTAINER_HOST_IPv6) { - return; + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date(Number(source) / 1e3 | 0)); + } + return dateToTag(source); } - if (url.hostname.includes("[")) { - if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i++] = value; + } } - } - else { - if (url.hostname === "localhost") { - return; + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key of Object.keys(sourceObject)) { + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } } - const ipComponents = url.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && - inRange(ipComponents[1]) && - inRange(ipComponents[2]) && - inRange(ipComponents[3]) && - ipComponents.length === 4) { - return; + } else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + } else if (ns.isDocumentSchema()) { + for (const key of Object.keys(sourceObject)) { + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); } + } + return newObject; } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); + return source; + } + flush() { + const buffer = cbor.serialize(this.value); + this.value = void 0; + return buffer; + } }; -exports.checkUrl = checkUrl; - - -/***/ }), - -/***/ 68712: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -const tslib_1 = __nccwpck_require__(61860); -const client_1 = __nccwpck_require__(5152); -const node_http_handler_1 = __nccwpck_require__(42402); -const property_provider_1 = __nccwpck_require__(56855); -const promises_1 = tslib_1.__importDefault(__nccwpck_require__(91943)); -const checkUrl_1 = __nccwpck_require__(1509); -const requestHelpers_1 = __nccwpck_require__(78914); -const retry_wrapper_1 = __nccwpck_require__(51122); -const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; -const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn - ? console.warn - : options.logger.warn.bind(options.logger); - if (relative && full) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } - else if (relative) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; - } - else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); +var CborShapeDeserializer = class { + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + read(schema, bytes) { + const data2 = cbor.deserialize(bytes); + return this.readValue(schema, data2); + } + /** + * Public because it's called by the protocol implementation to deserialize errors. + * @internal + */ + readValue(_schema, value) { + const ns = import_schema.NormalizedSchema.of(_schema); + if (ns.isTimestampSchema() && typeof value === "number") { + return (0, import_serde3.parseEpochTimestamp)(value); } - const url = new URL(host); - (0, checkUrl_1.checkUrl)(url, options.logger); - const requestHandler = new node_http_handler_1.NodeHttpHandler({ - requestTimeout: options.timeout ?? 1000, - connectionTimeout: options.timeout ?? 1000, - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url); - if (token) { - request.headers.Authorization = token; - } - else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") { + return value; + } else if (typeof value === "function" || typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + if (itemValue != null || sparse) { + newArray.push(itemValue); + } } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const targetSchema = ns.getValueSchema(); + for (const key of Object.keys(value)) { + const itemValue = this.readValue(targetSchema, value[key]); + if (itemValue != null || sparse) { + newObject[key] = itemValue; + } } - catch (e) { - throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); + } else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + newObject[key] = this.readValue(memberSchema, value[key]); } - }, options.maxRetries ?? 3, options.timeout ?? 1000); + } + return newObject; + } else { + return value; + } + } }; -exports.fromHttp = fromHttp; - - -/***/ }), - -/***/ 78914: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createGetRequest = createGetRequest; -exports.getCredentials = getCredentials; -const property_provider_1 = __nccwpck_require__(56855); -const protocol_http_1 = __nccwpck_require__(8821); -const smithy_client_1 = __nccwpck_require__(61411); -const util_stream_1 = __nccwpck_require__(35121); -function createGetRequest(url) { - return new protocol_http_1.HttpRequest({ - protocol: url.protocol, - hostname: url.hostname, - port: Number(url.port), - path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { - acc[k] = v; - return acc; - }, {}), - fragment: url.hash, +// src/submodules/cbor/SmithyRpcV2CborProtocol.ts +var SmithyRpcV2CborProtocol = class extends import_protocols2.RpcProtocol { + constructor({ defaultNamespace }) { + super({ defaultNamespace }); + this.codec = new CborCodec(); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + } + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType() }); -} -async function getCredentials(response, logger) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || - typeof parsed.SecretAccessKey !== "string" || - typeof parsed.Token !== "string" || - typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + - "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), - }; + if ((0, import_schema2.deref)(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + try { + request.headers["content-length"] = String(request.body.byteLength); + } catch (e) { + } } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } - catch (e) { } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { - Code: parsedBody.Code, - Message: parsedBody.Message, - }); + const { service, operation } = (0, import_util_middleware.getSmithyContext)(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } else { + request.path += path; } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); -} - - -/***/ }), - -/***/ 51122: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.retryWrapper = void 0; -const retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i = 0; i < maxRetries; ++i) { - try { - return await toRetry(); - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, delayMs)); - } - } - return await toRetry(); + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $response: response, + $fault: response.statusCode <= 500 ? "client" : "server" }; + const registry = import_schema2.TypeRegistry.for(namespace); + let errorSchema; + try { + errorSchema = registry.getSchema(errorName); + } catch (e) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const baseExceptionSchema = import_schema2.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = baseExceptionSchema.ctor; + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = import_schema2.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + throw Object.assign( + exception, + errorMetadata, + { + $fault: ns.getMergedTraits().error, + message + }, + output + ); + } + getDefaultContentType() { + return "application/cbor"; + } }; -exports.retryWrapper = retryWrapper; - - -/***/ }), - -/***/ 98605: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -var fromHttp_1 = __nccwpck_require__(68712); -Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 91338: +/***/ 13333: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -56826,289 +44489,252 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/event-streams/index.ts var index_exports = {}; __export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector + EventStreamSerde: () => EventStreamSerde }); module.exports = __toCommonJS(index_exports); -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(8821); -var import_querystring_builder = __nccwpck_require__(71649); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } +// src/submodules/event-streams/EventStreamSerde.ts +var import_schema = __nccwpck_require__(79724); +var import_util_utf8 = __nccwpck_require__(60791); +var EventStreamSerde = class { /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * Properties are injected by the HttpProtocol. */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { + constructor({ + marshaller, + serializer, + deserializer, + serdeContext, + defaultContentType + }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType } + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body + }; } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); + for await (const page of eventStream) { + yield page; } + } + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) + headers: event.headers, + body: event.body }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( + unionMember, + unionSchema, + event ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders + }; + return { + headers, + body + }; + }); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream for the end-user. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject + }; + } else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) + }; + } else { + return { + $unknown: event + }; + } }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(2564); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error( + "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." + ); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + } + }; } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); + /** + * @param unionMember - member name within the structure that contains an event stream union. + * @param unionSchema - schema of the union. + * @param event + * + * @returns the event body (bytes) and event type (string). + */ + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = unionSchema.hasMemberSchema(unionMember); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(import_schema.SCHEMA.DOCUMENT, value); + } else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } else { + type = "long"; + } + } else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } else if (memberSchema.isStringSchema()) { + type = "string"; + } else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } else { + serializer.write(eventSchema, event[unionMember]); + } + } else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); + } + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 91447: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 42402: +/***/ 97332: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __create = Object.create; @@ -57117,7 +44743,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -57140,792 +44765,901 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/protocols/index.ts var index_exports = {}; __export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + HttpProtocol: () => HttpProtocol, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath }); module.exports = __toCommonJS(index_exports); -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(8821); -var import_querystring_builder = __nccwpck_require__(71649); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(99542); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); }; -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +// src/submodules/protocols/HttpBindingProtocol.ts +var import_schema2 = __nccwpck_require__(79724); +var import_serde = __nccwpck_require__(99628); +var import_protocol_http2 = __nccwpck_require__(17898); +var import_util_stream2 = __nccwpck_require__(99542); + +// src/submodules/protocols/HttpProtocol.ts +var import_schema = __nccwpck_require__(79724); +var import_protocol_http = __nccwpck_require__(17898); +var HttpProtocol = class { + constructor(options) { + this.options = options; } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; + getRequestType() { + return import_protocol_http.HttpRequest; } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; + getResponseType() { + return import_protocol_http.HttpResponse; } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + for (const [k, v] of endpoint.url.searchParams.entries()) { + if (!request.query) { + request.query = {}; + } + request.query[k] = v; + } + return request; } else { - request.setTimeout(timeout, onTimeout); + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + return request; } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); } - if (sendBody) { - writeBody(httpRequest, request.body); + setHostPrefix(request, operationSchema, input) { + const operationNs = import_schema.NormalizedSchema.of(operationSchema); + const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter( + ([, member]) => member.getMergedTraits().hostLabel + ); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }; } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }); } - httpRequest.end(); -} -__name(writeBody, "writeBody"); - -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer }); } - static { - __name(this, "NodeHttpHandler"); - } /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * Loads eventStream capability async (for chunking). */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); + async loadEventStreamCapability() { + const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(13333))); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType() + }); } /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. + * @returns content-type default header value for event stream events and other documents. */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; + getDefaultContentType() { + throw new Error( + `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` + ); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + void schema; + void context; + void response; + void arg4; + void arg5; + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; + return context.eventStreamMarshaller; + } +}; + +// src/submodules/protocols/HttpBindingProtocol.ts +var HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ..._input ?? {} + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new import_protocol_http2.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns + }); + } + } else { + payload = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace( + `{${memberName}+}`, + replacement.split("/").map(extendedEncodeURIComponent).join("/") ); - return Date.now(); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); } + delete input[memberName]; + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } else { + hasNonHttpBindingMember = true; } } - return socketWarningTimestamp; + if (hasNonHttpBindingMember && input) { + serializer.write(schema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + // We pass on the traits to the sub-schema + // because we are still in the process of serializing the map itself. + ...traits, + httpQuery: key, + httpQueryParams: void 0 + }); + this.serializeQuery(valueSchema, val, query); } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer.push(serializable); } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; + } + query[traits.httpQuery] = buffer; + } else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } else { + dataObject = arg4; + } + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { + sections = (0, import_serde.splitEvery)(value, ",", 2); + } else { + sections = (0, import_serde.splitHeader)(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( + valueSchema, + value ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); + } + } + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; } else { - hostname = request.hostname; + nonHttpBindingMembers.push(memberName); } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + } + return nonHttpBindingMembers; + } +}; + +// src/submodules/protocols/RpcProtocol.ts +var import_schema3 = __nccwpck_require__(79724); +var import_protocol_http3 = __nccwpck_require__(17898); +var RpcProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest + }); } + } else { + serializer.write(schema, _input); + payload = serializer.flush(); } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); + } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema3.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; + } else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; } }; -// src/node-http2-handler.ts - - -var import_http22 = __nccwpck_require__(85675); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http4 = __nccwpck_require__(17898); -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); } - static { - __name(this, "NodeHttp2ConnectionPool"); + return resolvedPath2; +}; + +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); } + return new import_protocol_http4.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); } - offerLast(session) { - this.sessions.push(session); + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; } - contains(session) { - return this.sessions.includes(session); + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; + } + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; } }; -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var import_schema5 = __nccwpck_require__(79724); +var import_serde2 = __nccwpck_require__(99628); +var import_util_base64 = __nccwpck_require__(96039); +var import_util_utf8 = __nccwpck_require__(60791); + +// src/submodules/protocols/serde/determineTimestampFormat.ts +var import_schema4 = __nccwpck_require__(79724); +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { + return ns.getSchema(); } } - static { - __name(this, "NodeHttp2ConnectionManager"); + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; +} + +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var FromStringShapeDeserializer = class { + constructor(settings) { + this.settings = settings; } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); - } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; + read(_schema, data) { + const ns = import_schema5.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); } - if (!existingConnectionPool.contains(session)) { - return; + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); + case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(data); + case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); } - connectionPool.remove(session); + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); + } + return intermediateValue; } - this.sessionCache.delete(key); } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + switch (true) { + case ns.isNumericSchema(): + return Number(data); + case ns.isBigIntegerSchema(): + return BigInt(data); + case ns.isBigDecimalSchema(): + return new import_serde2.NumericValue(data, "bigDecimal"); + case ns.isBooleanSchema(): + return String(data).toLowerCase() === "true"; } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; + return data; } - getUrlString(request) { - return request.destination.toString(); + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); } }; -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); - } - static { - __name(this, "NodeHttp2Handler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); +// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts +var import_schema6 = __nccwpck_require__(79724); +var import_util_utf82 = __nccwpck_require__(60791); +var HttpInterceptingShapeDeserializer = class { + constructor(codecDeserializer, codecSettings) { + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); } - destroy() { - this.connectionManager.destroy(); + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } + read(schema, data) { + const ns = import_schema6.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; + if (typeof data === "string") { + return toBytes(data); } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); + return data; + } else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); + return data; } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + } + return this.codecDeserializer.read(ns, data); + } +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var import_schema8 = __nccwpck_require__(79724); + +// src/submodules/protocols/serde/ToStringShapeSerializer.ts +var import_schema7 = __nccwpck_require__(79724); +var import_serde3 = __nccwpck_require__(99628); +var import_util_base642 = __nccwpck_require__(96039); +var ToStringShapeSerializer = class { + constructor(settings) { + this.settings = settings; + this.stringBuffer = ""; + this.serdeContext = void 0; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + write(schema, value) { + const ns = import_schema7.NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error( + `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( + true + )}` + ); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: + this.stringBuffer = (0, import_serde3.dateToUtcString)(value); + break; + case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); } } -}; - -// src/stream-collector/collector.ts - -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; } }; -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var HttpInterceptingShapeSerializer = class { + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = import_schema8.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; } - isDone = done; + return this.codecSerializer.write(ns, value); } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + flush() { + if (this.buffer !== void 0) { + const buffer = this.buffer; + this.buffer = void 0; + return buffer; + } + return this.codecSerializer.flush(); } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); +}; // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 56855: -/***/ ((module) => { +/***/ 79724: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -57940,422 +45674,797 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/schema/index.ts var index_exports = {}; __export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + list: () => list, + map: () => map, + op: () => op, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + struct: () => struct }); module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; +// src/submodules/schema/deref.ts +var deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts +var import_protocol_http = __nccwpck_require__(17898); +var import_util_middleware = __nccwpck_require__(56182); +var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + try { + const parsed = await config.protocol.deserializeResponse( + operationSchema, + { + ...config, + ...context + }, + response + ); + return { + response, + output: parsed + }; + } catch (error2) { + Object.defineProperty(error2, "$response", { + value: response + }); + if (!("$metadata" in error2)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error2.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error2.$responseBodyText !== "undefined") { + if (error2.$response) { + error2.$response.body = error2.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error2.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { + } } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + throw error2; + } +}; +var findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +// src/submodules/schema/middleware/schemaSerializationMiddleware.ts +var import_util_middleware2 = __nccwpck_require__(56182); +var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint + }); + return next({ + ...args, + request + }); +}; + +// src/submodules/schema/middleware/getSchemaSerdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + } + }; +} + +// src/submodules/schema/TypeRegistry.ts +var TypeRegistry = class _TypeRegistry { + constructor(namespace, schemas = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; } static { - __name(this, "ProviderError"); + this.registries = /* @__PURE__ */ new Map(); } /** - * @deprecated use new operator. + * @param namespace - specifier. + * @returns the schema for that namespace, creating it if necessary. */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); + } + /** + * Adds the given schema to a type registry with the same namespace. + * + * @param shapeId - to be registered. + * @param schema - to be registered. + */ + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = _TypeRegistry.for(this.getNamespace(shapeId)); + registry.schemas.set(qualifiedName, schema); + } + /** + * @param shapeId - query. + * @returns the schema. + */ + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + /** + * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, + * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which + * is unique per service/model. + * + * This is generated under a unique prefix that is combined with the service namespace, and this + * method is used to retrieve it. + * + * The base exception synthetic schema is used when an error is returned by a service, but we cannot + * determine what existing schema to use to deserialize it. + * + * @returns the synthetic base exception of the service namespace associated with this registry instance. + */ + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } + } + return void 0; + } + /** + * @param predicate - criterion. + * @returns a schema in this registry matching the predicate. + */ + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + /** + * Unloads the current TypeRegistry. + */ + destroy() { + _TypeRegistry.registries.delete(this.namespace); + this.schemas.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; + } +}; + +// src/submodules/schema/schemas/Schema.ts +var Schema = class { + static assign(instance, values) { + const schema = Object.assign(instance, values); + TypeRegistry.for(schema.namespace).register(schema.name, schema); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +}; + +// src/submodules/schema/schemas/ListSchema.ts +var ListSchema = class _ListSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _ListSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/lis"); + } +}; +var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema +}); + +// src/submodules/schema/schemas/MapSchema.ts +var MapSchema = class _MapSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _MapSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/map"); + } +}; +var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema +}); + +// src/submodules/schema/schemas/OperationSchema.ts +var OperationSchema = class _OperationSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _OperationSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/ope"); + } +}; +var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output +}); + +// src/submodules/schema/schemas/StructureSchema.ts +var StructureSchema = class _StructureSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _StructureSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/str"); + } +}; +var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList +}); + +// src/submodules/schema/schemas/ErrorSchema.ts +var ErrorSchema = class _ErrorSchema extends StructureSchema { + constructor() { + super(...arguments); + this.symbol = _ErrorSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/err"); } }; +var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor +}); + +// src/submodules/schema/schemas/sentinels.ts +var SCHEMA = { + BLOB: 21, + // 21 + STREAMING_BLOB: 42, + // 42 + BOOLEAN: 2, + // 2 + STRING: 0, + // 0 + NUMERIC: 1, + // 1 + BIG_INTEGER: 17, + // 17 + BIG_DECIMAL: 19, + // 19 + DOCUMENT: 15, + // 15 + TIMESTAMP_DEFAULT: 4, + // 4 + TIMESTAMP_DATE_TIME: 5, + // 5 + TIMESTAMP_HTTP_DATE: 6, + // 6 + TIMESTAMP_EPOCH_SECONDS: 7, + // 7 + LIST_MODIFIER: 64, + // 64 + MAP_MODIFIER: 128 + // 128 +}; -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); +// src/submodules/schema/schemas/SimpleSchema.ts +var SimpleSchema = class _SimpleSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _SimpleSchema.symbol; } static { - __name(this, "CredentialsProviderError"); + this.symbol = Symbol.for("@smithy/sim"); } }; +var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef +}); -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { +// src/submodules/schema/schemas/NormalizedSchema.ts +var NormalizedSchema = class _NormalizedSchema { /** - * @override + * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. + * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + this.symbol = _NormalizedSchema.symbol; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema instanceof _NormalizedSchema) { + Object.assign(this, schema); + this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } } static { - __name(this, "TokenProviderError"); + this.symbol = Symbol.for("@smithy/nor"); } -}; - -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; + /** + * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. + */ + static of(ref) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + if (Array.isArray(ref)) { + const [ns, traits] = ref; + if (ns instanceof _NormalizedSchema) { + Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); + return ns; } - throw err; + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); } + return new _NormalizedSchema(ref); } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + /** + * @param indicator - numeric indicator for preset trait combination. + * @returns equivalent trait object. + */ + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i++ & 1) === 1) { + traits[trait] = 1; } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); } - if (isConstant) { - return resolved; + return traits; + } + /** + * @returns the underlying non-normalized schema. + */ + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + Object.assign(this, { schema: this.schema.getSchema() }); + return this.schema; } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + return deref(this.schema); + } + /** + * @param withNamespace - qualifies the name. + * @returns e.g. `MyShape` or `com.namespace#MyShape`. + */ + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; + } } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8821: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return this.name || void 0; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); + /** + * @returns the member name if the schema is a member schema. + * @throws Error when the schema isn't a member schema. + */ + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = __nccwpck_require__(40367); -var Field = class { - static { - __name(this, "Field"); + return this.memberName; } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; + isMemberSchema() { + return this._isMemberSchema; + } + isUnitSchema() { + return this.getSchema() === "unit"; } /** - * Appends a value to the field. - * - * @param value The value to append. + * boolean methods on this class help control flow in shape serialization and deserialization. */ - add(value) { - this.values.push(value); + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + } + return inner instanceof ListSchema; + } + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + } + return inner instanceof MapSchema; + } + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; + } + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isTimestampSchema() { + const schema = this.getSchema(); + return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; + } + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; + } + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; + } + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; + } + return this.getSchema() === SCHEMA.STREAMING_BLOB; } /** - * Overwrite existing field values. - * - * @param values The new field values. + * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. + * @returns whether the schema has the idempotencyToken trait. */ - set(values) { - this.values = values; + isIdempotencyToken() { + if (typeof this.traits === "number") { + return (this.traits & 4) === 4; + } else if (typeof this.traits === "object") { + return !!this.traits.idempotencyToken; + } + return false; } /** - * Remove all matching entries from list. - * - * @param value Value to remove. + * @returns own traits merged with member traits, where member traits of the same trait key take priority. + * This method is cached. */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }); } /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. + * @returns only the member traits. If the schema is not a member, this returns empty. */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); } /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. + * @returns only the traits inherent to the shape or member target shape if this schema is a member. + * If there are any member traits they are excluded. */ - get() { - return this.values; - } -}; - -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); } /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. + * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. * - * @param field The {@link Field} to set. + * @throws Error if the schema is not a Map or Document. */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; + getKeySchema() { + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); + } + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + if (typeof schema === "number") { + return this.memberFrom([63 & schema, 0], "key"); + } + return this.memberFrom([schema.keySchema, 0], "key"); } /** - * Retrieve {@link Field} entry by name. + * @returns the schema of the map's value or list's member. + * Returns a dummy Document schema if this schema is a Document. * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. + * @throws Error if the schema is not a Map, List, nor Document. */ - getField(name) { - return this.entries[name.toLowerCase()]; + getValueSchema() { + const schema = this.getSchema(); + if (typeof schema === "number") { + if (this.isMapSchema()) { + return this.memberFrom([63 & schema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([63 & schema, 0], "member"); + } + } + if (schema && typeof schema === "object") { + if (this.isStructSchema()) { + throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + } + const collection = schema; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return this.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([collection.valueSchema, 0], "member"); + } + } + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); } /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. + * @param member - to query. + * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + hasMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + return struct2.memberNames.includes(member); + } + return false; } /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. + * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` + * and will have the member name given. + * @param member - which member to retrieve and wrap. * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. + * @throws Error if member does not exist or the schema is neither a document nor structure. + * Note that errors are assumed to be structures and unions are considered structures for these purposes. */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + if (!struct2.memberNames.includes(member)) { + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); + } + const i = struct2.memberNames.indexOf(member); + const memberSchema = struct2.memberList[i]; + return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; + /** + * This can be used for checking the members as a hashmap. + * Prefer the structIterator method for iteration. + * + * This does NOT return list and map members, it is only for structures. + * + * @deprecated use (checked) structIterator instead. + * + * @returns a map of member names to member schemas (normalized). + */ + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } catch (ignored) { + } + return buffer; } /** - * Note: this does not deep-clone the body. + * @returns member name of event stream or empty string indicating none exists or this + * isn't a structure schema. */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } } - return cloned; + return ""; } /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. + * Allows iteration over members of a structure schema. + * Each yield is a pair of the member name and member schema. * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. + * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). */ - static isInstance(request) { - if (!request) { - return false; + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct2 = this.getSchema(); + for (let i = 0; i < struct2.memberNames.length; ++i) { + yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + * Creates a normalized member schema from the given schema and member name. */ - clone() { - return _HttpRequest.clone(this); - } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; + memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); + } + return new _NormalizedSchema(memberSchema, memberName); } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + /** + * @returns a last-resort human-readable name for the schema if it has no other identifiers. + */ + getSchemaName() { + const schema = this.getSchema(); + if (typeof schema === "number") { + const _schema = 63 & schema; + const container = 192 & schema; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; + } + } + return "Unknown"; } }; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 71649: +/***/ 99628: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -58370,884 +46479,663 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/serde/index.ts var index_exports = {}; __export(index_exports, { - buildQueryString: () => buildQueryString + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger, + nv: () => nv, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort }); module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(77291); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +// src/submodules/serde/copyDocumentWithTransform.ts +var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; - -/***/ }), - -/***/ 40367: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/serde/parse-utils.ts +var parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); +var expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3825: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(98832); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); + if (lower === "false") { + return false; } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); + if (lower === "true") { + return true; } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; -exports.fromBase64 = fromBase64; - - -/***/ }), - -/***/ 2564: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}; +var expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +var expectInt = expectLong; +var expectInt32 = (value) => expectSizedInt(value, 32); +var expectShort = (value) => expectSizedInt(value, 16); +var expectByte = (value) => expectSizedInt(value, 8); +var expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +var castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +var expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}; +var expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +var expectString = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +var expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; } - return to; + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(3825), module.exports); -__reExport(index_exports, __nccwpck_require__(54764), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 54764: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(98832); -const util_utf8_1 = __nccwpck_require__(73676); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } - else { - input = _input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); - } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +var strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); }; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 98832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); } - return to; + return parseFloat(value); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(91447); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); +var limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + return expectNumber(value); +}; +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 48686: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + return expectFloat32(value); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; +var strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); + return expectLong(value); +}; +var strictParseInt = strictParseLong; +var strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } + return expectInt32(value); +}; +var strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; + return expectShort(value); +}; +var strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 16359: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; - } -} -exports.ByteArrayCollector = ByteArrayCollector; - - -/***/ }), - -/***/ 95068: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 59138: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; + return expectByte(value); +}; +var stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}; +var logger = { + warn: console.warn +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(2564); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); - } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); - } +// src/submodules/serde/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; } -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 19784: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(2564); -const stream_type_check_1 = __nccwpck_require__(89855); -const ChecksumStream_browser_1 = __nccwpck_require__(95068); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) + ); + } + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +var parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); +}; +var buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}; +var parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); + } + return input; +}; +var parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +var isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +var parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +var parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; +}; +var parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; +}; +var stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); }; -exports.createChecksumStream = createChecksumStream; - - -/***/ }), - -/***/ 57918: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// src/submodules/serde/generateIdempotencyToken.ts +var import_uuid = __nccwpck_require__(12048); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(89855); -const ChecksumStream_1 = __nccwpck_require__(59138); -const createChecksumStream_browser_1 = __nccwpck_require__(19784); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); +// src/submodules/serde/lazy-json.ts +var LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); } - return new ChecksumStream_1.ChecksumStream(init); -} - - -/***/ }), - -/***/ 66738: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(16359); -const createBufferedReadableStream_1 = __nccwpck_require__(38802); -const stream_type_check_1 = __nccwpck_require__(89855); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; +// src/submodules/serde/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; } - -/***/ }), - -/***/ 38802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(16359); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; +// src/submodules/serde/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } else { + currentSegment += delimiter + segments[i]; } - if (typeof chunk === "string") { - return 0; + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } - return -1; + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; } - -/***/ }), - -/***/ 23927: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; - - -/***/ }), - -/***/ 75469: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; +// src/submodules/serde/split-header.ts +var splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; } - if (byteLengthCounter >= bytes) { - break; + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; } - isDone = done; + break; + default: } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; } - return collected; -} - - -/***/ }), - -/***/ 15139: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(75469); -const stream_type_check_1 = __nccwpck_require__(89855); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); + return v.replace(/\\"/g, '"'); + }); }; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; - } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); + +// src/submodules/serde/value/NumericValue.ts +var NumericValue = class _NumericValue { + constructor(string, type) { + this.string = string; + this.type = type; + let dot = 0; + for (let i = 0; i < string.length; ++i) { + const char = string.charCodeAt(i); + if (i === 0 && char === 45) { + continue; + } + if (char === 46) { + if (dot) { + throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); } - callback(); + dot = 1; + continue; + } + if (char < 48 || char > 57) { + throw new Error( + `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` + ); + } + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); + if (prototypeMatch) { + return prototypeMatch; + } + if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { + return true; } + return prototypeMatch; + } +}; +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); } +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 35121: +/***/ 83879: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -59267,77 +47155,245 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(2564); -var import_util_utf8 = __nccwpck_require__(73676); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(17898); +var import_querystring_builder = __nccwpck_require__(31622); + +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); } -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); } -__name(transformFromString, "transformFromString"); +__name(requestTimeout, "requestTimeout"); -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { static { - __name(this, "Uint8ArrayBlobAdapter"); + __name(this, "FetchHttpHandler"); } /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } + return new _FetchHttpHandler(instanceOrOptions); } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); + } } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; } }; -// src/index.ts -__reExport(index_exports, __nccwpck_require__(59138), module.exports); -__reExport(index_exports, __nccwpck_require__(57918), module.exports); -__reExport(index_exports, __nccwpck_require__(66738), module.exports); -__reExport(index_exports, __nccwpck_require__(23927), module.exports); -__reExport(index_exports, __nccwpck_require__(15139), module.exports); -__reExport(index_exports, __nccwpck_require__(94202), module.exports); -__reExport(index_exports, __nccwpck_require__(86557), module.exports); -__reExport(index_exports, __nccwpck_require__(89855), module.exports); +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(96039); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -59346,216 +47402,181 @@ __reExport(index_exports, __nccwpck_require__(89855), module.exports); /***/ }), -/***/ 6324: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 77544: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(91338); -const util_base64_1 = __nccwpck_require__(2564); -const util_hex_encoding_1 = __nccwpck_require__(48686); -const util_utf8_1 = __nccwpck_require__(73676); -const stream_type_check_1 = __nccwpck_require__(89855); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 94202: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(42402); -const util_buffer_from_1 = __nccwpck_require__(98832); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(6324); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ 80155: -/***/ ((__unused_webpack_module, exports) => { +// src/index.ts +var index_exports = {}; +__export(index_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(index_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); -} /***/ }), -/***/ 86557: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(80155); -const stream_type_check_1 = __nccwpck_require__(89855); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); - } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} +/***/ 88037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ }), +// src/index.ts +var index_exports = {}; +__export(index_exports, { + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption +}); +module.exports = __toCommonJS(index_exports); -/***/ 89855: -/***/ ((__unused_webpack_module, exports) => { +// src/deserializerMiddleware.ts +var import_protocol_http = __nccwpck_require__(17898); +var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { + } + } + throw error; + } +}, "deserializerMiddleware"); +var findHeader = /* @__PURE__ */ __name((pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}, "findHeader"); -"use strict"; +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true }; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true }; -exports.isBlob = isBlob; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: /* @__PURE__ */ __name((commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, "applyToStack") + }; +} +__name(getSerdePlugin, "getSerdePlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 77291: -/***/ ((module) => { +/***/ 39417: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -59568,377 +47589,788 @@ var __copyProps = (to, from, except, desc) => { if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return to; + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(index_exports); + +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(17898); +var import_querystring_builder = __nccwpck_require__(31622); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); + +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); + +// src/timing.ts +var timing = { + setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), + clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + static { + __name(this, "NodeHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +// src/node-http2-handler.ts -/***/ }), +var import_http22 = __nccwpck_require__(85675); -/***/ 73676: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(index_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(98832); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); + static { + __name(this, "NodeHttp2ConnectionPool"); } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; + offerLast(session) { + this.sessions.push(session); } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + contains(session) { + return this.sessions.includes(session); } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 75869: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } } - return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromIni: () => fromIni -}); -module.exports = __toCommonJS(index_exports); - -// src/fromIni.ts - - -// src/resolveProfileData.ts - -// src/resolveAssumeRoleCredentials.ts - - -var import_shared_ini_file_loader = __nccwpck_require__(46459); - -// src/resolveCredentialSource.ts -var import_client = __nccwpck_require__(5152); -var import_property_provider = __nccwpck_require__(78215); -var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { - const sourceProvidersMap = { - EcsContainer: /* @__PURE__ */ __name(async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(98605))); - const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, "EcsContainer"), - Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, "Ec2InstanceMetadata"), - Environment: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(55606))); - return async () => fromEnv(options)().then(setNamedProvider); - }, "Environment") - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } else { - throw new import_property_provider.CredentialsProviderError( - `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, - { logger } - ); +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } } -}, "resolveCredentialSource"); -var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); - -// src/resolveAssumeRoleCredentials.ts -var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { - return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); -}, "isAssumeRoleProfile"); -var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + static { + __name(this, "NodeHttp2ConnectionManager"); } - return withSourceProfile; -}, "isAssumeRoleWithSourceProfile"); -var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); + } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - return withProviderProfile; -}, "isCredentialSourceProfile"); -var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(1136))); - options.roleAssumer = getDefaultRoleAssumer( - { - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); } - }, - options.clientPlugins - ); + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } } - if (source_profile && source_profile in visitedProfiles) { - throw new import_property_provider.CredentialsProviderError( - `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), - { logger: options.logger } - ); + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; } - options.logger?.debug( - `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` - ); - const sourceCredsProvider = source_profile ? resolveProfileData( - source_profile, - profiles, - options, - { - ...visitedProfiles, - [source_profile]: true - }, - isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) - ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new import_property_provider.CredentialsProviderError( - `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, - { logger: options.logger, tryNextLink: false } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +}; + +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } + }); + } + static { + __name(this, "NodeHttp2Handler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttp2Handler(instanceOrOptions); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) ); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") - ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); } -}, "resolveAssumeRoleCredentials"); -var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { - return !section.role_arn && !!section.credential_source; -}, "isCredentialSourceWithoutRoleArn"); - -// src/resolveProcessCredentials.ts - -var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); -var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(75360))).then( - ({ fromProcess }) => fromProcess({ - ...options, - profile - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) -), "resolveProcessCredentials"); - -// src/resolveSsoCredentials.ts - -var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60998))); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig - })().then((creds) => { - if (profileData.sso_session) { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } else { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); } - }); -}, "resolveSsoCredentials"); -var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); - -// src/resolveStaticCredentials.ts - -var isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); -var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, - ...profile.aws_account_id && { accountId: profile.aws_account_id } - }; - return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); -}, "resolveStaticCredentials"); - -// src/resolveWebIdentityCredentials.ts + } +}; -var isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile"); -var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(29956))).then( - ({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) -), "resolveWebIdentityCredentials"); +// src/stream-collector/collector.ts -// src/resolveProfileData.ts -var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); + static { + __name(this, "Collector"); } - if (isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); } - if (isWebIdentityProfile(data)) { - return resolveWebIdentityCredentials(data, options); +}; + +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); } - if (isProcessProfile(data)) { - return resolveProcessCredentials(options, profileName); + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; } - if (isSsoProfile(data)) { - return await resolveSsoCredentials(profileName, data, options); + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; } - throw new import_property_provider.CredentialsProviderError( - `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, - { logger: options.logger } - ); -}, "resolveProfileData"); - -// src/fromIni.ts -var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProfileData( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: _init.profile ?? callerClientConfig?.profile - }), - profiles, - init - ); -}, "fromIni"); + return collected; +} +__name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -59947,7 +48379,7 @@ var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig /***/ }), -/***/ 78215: +/***/ 6180: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -60117,85 +48549,7 @@ var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { /***/ }), -/***/ 27981: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; - - -/***/ }), - -/***/ 68282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(27981); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; - - -/***/ }), - -/***/ 33517: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(68282); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; - - -/***/ }), - -/***/ 46459: +/***/ 17898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -60215,201 +48569,238 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(27981), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(68282), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(33517); - -// src/loadSharedConfigFiles.ts +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); -// src/getConfigData.ts -var import_types = __nccwpck_require__(20351); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; +// src/Field.ts +var import_types = __nccwpck_require__(34048); +var Field = class { + static { + __name(this, "Field"); } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(27981); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(27981); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(27981); - -// src/parseIni.ts - -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } - } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); } - return map; -}, "parseIni"); + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(31221); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + static { + __name(this, "Fields"); + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(31221); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +// src/httpRequest.ts -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); } + return cloned; } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(33517); -var import_slurpFile3 = __nccwpck_require__(31221); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; + +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -60418,32 +48809,64 @@ var externalDataInterceptor = { /***/ }), -/***/ 31221: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 31622: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(index_exports); +var import_util_uri_escape = __nccwpck_require__(13288); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; + } + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 20351: +/***/ 34048: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -60514,388 +48937,67 @@ var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { const checksumAlgorithms = []; if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5861: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, - credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, - defaultProvider: () => defaultProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultProvider.ts -var import_credential_provider_env = __nccwpck_require__(55606); - -var import_shared_ini_file_loader = __nccwpck_require__(35); - -// src/remoteProvider.ts -var import_property_provider = __nccwpck_require__(22335); -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var remoteProvider = /* @__PURE__ */ __name(async (init) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(98605))); - return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); - }; - } - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init); -}, "remoteProvider"); - -// src/defaultProvider.ts -var multipleCredentialSourceWarningEmitted = false; -var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - async () => { - const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn; - warnFn( - `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -` - ); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init.logger, - tryNextLink: true - }); - } - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return (0, import_credential_provider_env.fromEnv)(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new import_property_provider.CredentialsProviderError( - "Skipping SSO provider in default chain (inputs do not include SSO fields).", - { logger: init.logger } - ); - } - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60998))); - return fromSSO(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(75869))); - return fromIni(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(75360))); - return fromProcess(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(29956))); - return fromTokenFile(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger - }); - } - ), - credentialsTreatedAsExpired, - credentialsWillNeedRefresh -), "defaultProvider"); -var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); -var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 22335: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); - -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - static { - __name(this, "CredentialsProviderError"); + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); } -}; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -60904,86 +49006,90 @@ var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { /***/ }), -/***/ 63733: +/***/ 73464: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(45217); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; -exports.getHomeDir = getHomeDir; +exports.fromBase64 = fromBase64; /***/ }), -/***/ 51586: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 96039: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(63733); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(73464), module.exports); +__reExport(index_exports, __nccwpck_require__(71189), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 12197: +/***/ 71189: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(51586); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(45217); +const util_utf8_1 = __nccwpck_require__(60791); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); }; -exports.getSSOTokenFromFile = getSSOTokenFromFile; +exports.toBase64 = toBase64; /***/ }), -/***/ 35: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 24192: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -61002,201 +49108,37 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + calculateBodyLength: () => calculateBodyLength }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(63733), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(51586), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(12197); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(39831); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(63733); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(63733); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(63733); -// src/parseIni.ts - -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } +// src/calculateBodyLength.ts +var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; +var calculateBodyLength = /* @__PURE__ */ __name((body) => { + if (typeof body === "string") { + if (TEXT_ENCODER) { + return TEXT_ENCODER.encode(body).byteLength; } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(31325); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(31325); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); - -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } + let len = body.length; + for (let i = len - 1; i >= 0; i--) { + const code = body.charCodeAt(i); + if (code > 127 && code <= 2047) len++; + else if (code > 2047 && code <= 65535) len += 2; + if (code >= 56320 && code <= 57343) i--; } + return len; + } else if (typeof body.byteLength === "number") { + return body.byteLength; + } else if (typeof body.size === "number") { + return body.size; } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); - -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(12197); -var import_slurpFile3 = __nccwpck_require__(31325); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; + throw new Error(`Body Length computation failed for ${body}`); +}, "calculateBodyLength"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -61205,32 +49147,58 @@ var externalDataInterceptor = { /***/ }), -/***/ 31325: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 45217: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -exports.slurpFile = slurpFile; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(index_exports); +var import_is_array_buffer = __nccwpck_require__(77544); +var import_buffer = __nccwpck_require__(20181); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 39831: +/***/ 96369: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -61255,113 +49223,44 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + fromHex: () => fromHex, + toHex: () => toHex }); module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); + } + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} +__name(toHex, "toHex"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -61370,11 +49269,9 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 75360: +/***/ 56182: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -61397,348 +49294,528 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - fromProcess: () => fromProcess + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider }); module.exports = __toCommonJS(index_exports); -// src/fromProcess.ts -var import_shared_ini_file_loader = __nccwpck_require__(23074); +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(34048); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); -// src/resolveProcessCredentials.ts -var import_property_provider = __nccwpck_require__(41508); -var import_child_process = __nccwpck_require__(35317); -var import_util = __nccwpck_require__(39023); +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); +// Annotate the CommonJS export names for ESM import in node: -// src/getValidatedProcessCredentials.ts -var import_client = __nccwpck_require__(5152); -var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); +0 && (0); + + + +/***/ }), + +/***/ 40238: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; } - } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...data.SessionToken && { sessionToken: data.SessionToken }, - ...data.Expiration && { expiration: new Date(data.Expiration) }, - ...data.CredentialScope && { credentialScope: data.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; -}, "getValidatedProcessCredentials"); + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; -// src/resolveProcessCredentials.ts -var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = (0, import_util.promisify)(import_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; + +/***/ }), + +/***/ 96783: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 65697: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(96039); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); + } + _read(size) { } + _write(chunk, encoding, callback) { try { - data = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + this.checksum.update(chunk); + this.push(chunk); } - return getValidatedProcessCredentials(profileName, data, profiles); - } catch (error) { - throw new import_property_provider.CredentialsProviderError(error.message, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + catch (e) { + return callback(e); + } + return callback(); } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger - }); - } -}, "resolveProcessCredentials"); + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); + } +} +exports.ChecksumStream = ChecksumStream; -// src/fromProcess.ts -var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProcessCredentials( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }), - profiles, - init.logger - ); -}, "fromProcess"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +/***/ }), + +/***/ 49671: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(96039); +const stream_type_check_1 = __nccwpck_require__(83040); +const ChecksumStream_browser_1 = __nccwpck_require__(96783); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; /***/ }), -/***/ 41508: -/***/ ((module) => { +/***/ 8921: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(83040); +const ChecksumStream_1 = __nccwpck_require__(65697); +const createChecksumStream_browser_1 = __nccwpck_require__(49671); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); + } + return new ChecksumStream_1.ChecksumStream(init); +} -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; + +/***/ }), + +/***/ 42823: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(40238); +const createBufferedReadableStream_1 = __nccwpck_require__(80383); +const stream_type_check_1 = __nccwpck_require__(83040); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; +/***/ }), -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); +/***/ 80383: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +"use strict"; -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(40238); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); } - if (isConstant) { - return resolved; +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + if (chunk instanceof Uint8Array) { + return 1; } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + if (typeof chunk === "string") { + return 0; + } + return -1; +} /***/ }), -/***/ 53798: +/***/ 40588: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; }; -exports.getHomeDir = getHomeDir; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; /***/ }), -/***/ 16335: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 44168: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(53798); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} /***/ }), -/***/ 66204: +/***/ 91390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(16335); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(44168); +const stream_type_check_1 = __nccwpck_require__(83040); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); }; -exports.getSSOTokenFromFile = getSSOTokenFromFile; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} /***/ }), -/***/ 23074: +/***/ 99542: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -61764,229 +49841,284 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(53798), module.exports); -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(96039); +var import_util_utf8 = __nccwpck_require__(60791); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); + } + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); + } + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static { + __name(this, "Uint8ArrayBlobAdapter"); + } + /** + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + */ + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + } + /** + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. + */ + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; + } + /** + * @param encoding - default 'utf-8'. + * @returns the blob as string. + */ + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } +}; // src/index.ts -__reExport(index_exports, __nccwpck_require__(16335), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(66204); +__reExport(index_exports, __nccwpck_require__(65697), module.exports); +__reExport(index_exports, __nccwpck_require__(8921), module.exports); +__reExport(index_exports, __nccwpck_require__(42823), module.exports); +__reExport(index_exports, __nccwpck_require__(40588), module.exports); +__reExport(index_exports, __nccwpck_require__(91390), module.exports); +__reExport(index_exports, __nccwpck_require__(34367), module.exports); +__reExport(index_exports, __nccwpck_require__(32638), module.exports); +__reExport(index_exports, __nccwpck_require__(83040), module.exports); +// Annotate the CommonJS export names for ESM import in node: -// src/loadSharedConfigFiles.ts +0 && (0); -// src/getConfigData.ts -var import_types = __nccwpck_require__(82688); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(53798); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); +/***/ }), + +/***/ 51113: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(83879); +const util_base64_1 = __nccwpck_require__(96039); +const util_hex_encoding_1 = __nccwpck_require__(96369); +const util_utf8_1 = __nccwpck_require__(60791); +const stream_type_check_1 = __nccwpck_require__(83040); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; -// src/getCredentialsFilepath.ts -var import_getHomeDir2 = __nccwpck_require__(53798); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); +/***/ }), -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(53798); +/***/ 34367: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/parseIni.ts +"use strict"; -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(39417); +const util_buffer_from_1 = __nccwpck_require__(45217); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(51113); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } - } } - } - return map; -}, "parseIni"); + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(16332); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); -// src/getSsoSessionData.ts +/***/ }), -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); +/***/ 13480: +/***/ ((__unused_webpack_module, exports) => { -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(16332); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +"use strict"; -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); } - } - return merged; -}, "mergeConfigFiles"); + const readableStream = stream; + return readableStream.tee(); +} -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(66204); -var import_slurpFile3 = __nccwpck_require__(16332); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; -// Annotate the CommonJS export names for ESM import in node: +/***/ }), -0 && (0); +/***/ 32638: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(13480); +const stream_type_check_1 = __nccwpck_require__(83040); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} /***/ }), -/***/ 16332: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 83040: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); }; -exports.slurpFile = slurpFile; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; /***/ }), -/***/ 82688: +/***/ 13288: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -62011,113 +50143,20 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath }); module.exports = __toCommonJS(index_exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -62126,19 +50165,14 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 60998: +/***/ 60791: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -62153,221 +50187,120 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/loadSso.ts -var loadSso_exports = {}; -__export(loadSso_exports, { - GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, - SSOClient: () => import_client_sso.SSOClient -}); -var import_client_sso; -var init_loadSso = __esm({ - "src/loadSso.ts"() { - "use strict"; - import_client_sso = __nccwpck_require__(62054); - } -}); - // src/index.ts var index_exports = {}; __export(index_exports, { - fromSSO: () => fromSSO, - isSsoProfile: () => isSsoProfile, - validateSsoProfile: () => validateSsoProfile + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 }); module.exports = __toCommonJS(index_exports); -// src/fromSSO.ts - - - -// src/isSsoProfile.ts -var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(45217); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); -// src/resolveSSOCredentials.ts -var import_client = __nccwpck_require__(5152); -var import_token_providers = __nccwpck_require__(75433); -var import_property_provider = __nccwpck_require__(38430); -var import_shared_ini_file_loader = __nccwpck_require__(14876); -var SHOULD_FAIL_CREDENTIAL_CHAIN = false; -var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig, - parentClientConfig, - profile, - logger -}) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await (0, import_token_providers.fromSso)({ profile })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } else { - try { - token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); - const sso = ssoClient || new SSOClient2( - Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion - }) - ); - let ssoResp; - try { - ssoResp = await sso.send( - new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - }) - ); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } - const { - roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} - } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); - } else { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; } - return credentials; -}, "resolveSSOCredentials"); + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: -// src/validateSsoProfile.ts +0 && (0); -var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { - const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; - if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { - throw new import_property_provider.CredentialsProviderError( - `Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join( - ", " - )} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, - { tryNextLink: false, logger } - ); + + +/***/ }), + +/***/ 55606: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return profile; -}, "validateSsoProfile"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/fromSSO.ts -var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const session = ssoSessions[profile.sso_session]; - const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; - if (ssoRegion && ssoRegion !== session.sso_region) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - profile.sso_region = session.sso_region; - profile.sso_start_url = session.sso_start_url; - } - const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile( - profile, - init.logger - ); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new import_property_provider.CredentialsProviderError( - 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', - { tryNextLink: false, logger: init.logger } - ); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, + ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, + ENV_EXPIRATION: () => ENV_EXPIRATION, + ENV_KEY: () => ENV_KEY, + ENV_SECRET: () => ENV_SECRET, + ENV_SESSION: () => ENV_SESSION, + fromEnv: () => fromEnv +}); +module.exports = __toCommonJS(index_exports); + +// src/fromEnv.ts +var import_client = __nccwpck_require__(5152); +var import_property_provider = __nccwpck_require__(29006); +var ENV_KEY = "AWS_ACCESS_KEY_ID"; +var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; +var ENV_SESSION = "AWS_SESSION_TOKEN"; +var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; +var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; +var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; +var fromEnv = /* @__PURE__ */ __name((init) => async () => { + init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...sessionToken && { sessionToken }, + ...expiry && { expiration: new Date(expiry) }, + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; } -}, "fromSSO"); + throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); +}, "fromEnv"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -62376,7 +50309,7 @@ var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig /***/ }), -/***/ 38430: +/***/ 29006: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -62546,334 +50479,239 @@ var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { /***/ }), -/***/ 4484: +/***/ 1509: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; +exports.checkUrl = void 0; +const property_provider_1 = __nccwpck_require__(56855); +const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; +const LOOPBACK_CIDR_IPv6 = "::1/128"; +const ECS_CONTAINER_HOST = "169.254.170.2"; +const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; +const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; +const checkUrl = (url, logger) => { + if (url.protocol === "https:") { + return; } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; - - -/***/ }), - -/***/ 66773: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(4484); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); + if (url.hostname === ECS_CONTAINER_HOST || + url.hostname === EKS_CONTAINER_HOST_IPv4 || + url.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url.hostname.includes("[")) { + if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } + else { + if (url.hostname === "localhost") { + return; + } + const ipComponents = url.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && + inRange(ipComponents[1]) && + inRange(ipComponents[2]) && + inRange(ipComponents[3]) && + ipComponents.length === 4) { + return; + } + } + throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); }; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +exports.checkUrl = checkUrl; /***/ }), -/***/ 26518: +/***/ 68712: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(66773); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; +exports.fromHttp = void 0; +const tslib_1 = __nccwpck_require__(61860); +const client_1 = __nccwpck_require__(5152); +const node_http_handler_1 = __nccwpck_require__(42402); +const property_provider_1 = __nccwpck_require__(56855); +const promises_1 = tslib_1.__importDefault(__nccwpck_require__(91943)); +const checkUrl_1 = __nccwpck_require__(1509); +const requestHelpers_1 = __nccwpck_require__(78914); +const retry_wrapper_1 = __nccwpck_require__(51122); +const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; +const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn + ? console.warn + : options.logger.warn.bind(options.logger); + if (relative && full) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsFullUri will take precedence."); } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; - - -/***/ }), - -/***/ 14876: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(4484), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(66773), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(26518); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(30650); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(4484); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(4484); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(4484); - -// src/parseIni.ts - -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationToken will take precedence."); } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(67438); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); + if (full) { + host = full; + } + else if (relative) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; + } + else { + throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url = new URL(host); + (0, checkUrl_1.checkUrl)(url, options.logger); + const requestHandler = new node_http_handler_1.NodeHttpHandler({ + requestTimeout: options.timeout ?? 1000, + connectionTimeout: options.timeout ?? 1000, + }); + return (0, retry_wrapper_1.retryWrapper)(async () => { + const request = (0, requestHelpers_1.createGetRequest)(url); + if (token) { + request.headers.Authorization = token; + } + else if (tokenFile) { + request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + } + try { + const result = await requestHandler.handle(request); + return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + } + catch (e) { + throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1000); +}; +exports.fromHttp = fromHttp; -// src/getSsoSessionData.ts -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); +/***/ }), -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(67438); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +/***/ 78914: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createGetRequest = createGetRequest; +exports.getCredentials = getCredentials; +const property_provider_1 = __nccwpck_require__(56855); +const protocol_http_1 = __nccwpck_require__(8821); +const smithy_client_1 = __nccwpck_require__(61411); +const util_stream_1 = __nccwpck_require__(35121); +function createGetRequest(url) { + return new protocol_http_1.HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: Number(url.port), + path: url.pathname, + query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { + acc[k] = v; + return acc; + }, {}), + fragment: url.hash, + }); +} +async function getCredentials(response, logger) { + const stream = (0, util_stream_1.sdkStreamMixin)(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || + typeof parsed.SecretAccessKey !== "string" || + typeof parsed.Token !== "string" || + typeof parsed.Expiration !== "string") { + throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), + }; } - } - return merged; -}, "mergeConfigFiles"); + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } + catch (e) { } + throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { + Code: parsedBody.Code, + Message: parsedBody.Message, + }); + } + throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); +} -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(26518); -var import_slurpFile3 = __nccwpck_require__(67438); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; -// Annotate the CommonJS export names for ESM import in node: +/***/ }), -0 && (0); +/***/ 51122: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.retryWrapper = void 0; +const retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i = 0; i < maxRetries; ++i) { + try { + return await toRetry(); + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return await toRetry(); + }; +}; +exports.retryWrapper = retryWrapper; /***/ }), -/***/ 67438: +/***/ 98605: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; +exports.fromHttp = void 0; +var fromHttp_1 = __nccwpck_require__(68712); +Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); /***/ }), -/***/ 30650: -/***/ ((module) => { +/***/ 91338: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -62897,898 +50735,1087 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(8821); +var import_querystring_builder = __nccwpck_require__(71649); -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} +__name(requestTimeout, "requestTimeout"); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { + static { + __name(this, "FetchHttpHandler"); } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 88079: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromTokenFile = void 0; -const client_1 = __nccwpck_require__(5152); -const property_provider_1 = __nccwpck_require__(51264); -const fs_1 = __nccwpck_require__(79896); -const fromWebToken_1 = __nccwpck_require__(34453); -const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; -const ENV_ROLE_ARN = "AWS_ROLE_ARN"; -const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; -const fromTokenFile = (init = {}) => async () => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; } - return credentials; + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } }; -exports.fromTokenFile = fromTokenFile; + +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(2564); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 34453: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 91447: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; +// src/index.ts +var index_exports = {}; +__export(index_exports, { + isArrayBuffer: () => isArrayBuffer }); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(1136))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); - } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, - }); -}; -exports.fromWebToken = fromWebToken; +module.exports = __toCommonJS(index_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 29956: +/***/ 42402: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return to; + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(index_exports); + +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(8821); +var import_querystring_builder = __nccwpck_require__(71649); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); + +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); + +// src/timing.ts +var timing = { + setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), + clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + static { + __name(this, "NodeHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(88079), module.exports); -__reExport(index_exports, __nccwpck_require__(34453), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +// src/node-http2-handler.ts -/***/ }), +var import_http22 = __nccwpck_require__(85675); -/***/ 51264: -/***/ ((module) => { +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); - -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; + static { + __name(this, "NodeHttp2ConnectionPool"); + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - static { - __name(this, "ProviderError"); + offerLast(session) { + this.sessions.push(session); } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); + contains(session) { + return this.sessions.includes(session); } -}; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); } - static { - __name(this, "CredentialsProviderError"); + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } } }; -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } } static { - __name(this, "TokenProviderError"); - } -}; - -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); + __name(this, "NodeHttp2ConnectionManager"); } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; } - throw err; } - } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + if (!existingConnectionPool.contains(session)) { + return; } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 52590: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getHostHeaderPlugin: () => getHostHeaderPlugin, - hostHeaderMiddleware: () => hostHeaderMiddleware, - hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, - resolveHostHeaderConfig: () => resolveHostHeaderConfig -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(99252); -function resolveHostHeaderConfig(input) { - return input; -} -__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); -var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) return next(args); - const { request } = args; - const { handlerProtocol = "" } = options.requestHandler.metadata || {}; - if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { - delete request.headers["host"]; - request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); - } else if (!request.headers["host"]) { - let host = request.hostname; - if (request.port != null) host += `:${request.port}`; - request.headers["host"] = host; + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); } - return next(args); -}, "hostHeaderMiddleware"); -var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true -}; -var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, "applyToStack") -}), "getHostHeaderPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 99252: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = __nccwpck_require__(51026); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; + getUrlString(request) { + return request.destination.toString(); } }; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } + }); } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; + __name(this, "NodeHttp2Handler"); } /** - * Note: this does not deep-clone the body. + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - return cloned; + return new _NodeHttp2Handler(instanceOrOptions); } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; } /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + * Destroys a session. + * @param session - the session to destroy. */ - clone() { - return _HttpRequest.clone(this); + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } } }; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); +// src/stream-collector/collector.ts + +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; + static { + __name(this, "Collector"); } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); } }; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 51026: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -63797,11 +51824,9 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 85242: +/***/ 56855: /***/ ((module) => { -"use strict"; - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -63824,162 +51849,152 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - getLoggerPlugin: () => getLoggerPlugin, - loggerMiddleware: () => loggerMiddleware, - loggerMiddlewareOptions: () => loggerMiddlewareOptions + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(index_exports); -// src/loggerMiddleware.ts -var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - output: outputFilterSensitiveLog(outputWithoutMetadata), - metadata: $metadata - }); - return response; - } catch (error) { - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata - }); - throw error; +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } -}, "loggerMiddleware"); -var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true -}; -var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, "applyToStack") -}), "getLoggerPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 81568: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + static { + __name(this, "ProviderError"); + } + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } - return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getRecursionDetectionPlugin: () => getRecursionDetectionPlugin -}); -module.exports = __toCommonJS(index_exports); -// src/configuration.ts -var recursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + static { + __name(this, "CredentialsProviderError"); + } }; -// src/getRecursionDetectionPlugin.ts -var import_recursionDetectionMiddleware = __nccwpck_require__(22521); -var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add((0, import_recursionDetectionMiddleware.recursionDetectionMiddleware)(), recursionDetectionMiddlewareOptions); - }, "applyToStack") -}), "getRecursionDetectionPlugin"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(22521), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); + } + static { + __name(this, "TokenProviderError"); + } +}; -/***/ 22521: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}, "chain"); -"use strict"; +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.recursionDetectionMiddleware = void 0; -const lambda_invoke_store_1 = __nccwpck_require__(37453); -const protocol_http_1 = __nccwpck_require__(24138); -const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -const recursionDetectionMiddleware = () => (next) => async (args) => { - const { request } = args; - if (!protocol_http_1.HttpRequest.isInstance(request)) { - return next(args); +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? - TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceIdFromEnv = process.env[ENV_TRACE_ID]; - const traceIdFromInvokeStore = lambda_invoke_store_1.InvokeStore.getXRayTraceId(); - const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; - const nonEmptyString = (str) => typeof str === "string" && str.length > 0; - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); } - return next({ - ...args, - request, - }); -}; -exports.recursionDetectionMiddleware = recursionDetectionMiddleware; + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 24138: +/***/ 8821: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -64039,7 +52054,7 @@ var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensi }, "resolveHttpHandlerRuntimeConfig"); // src/Field.ts -var import_types = __nccwpck_require__(24064); +var import_types = __nccwpck_require__(40367); var Field = class { static { __name(this, "Field"); @@ -64216,390 +52231,21 @@ var HttpResponse = class { this.statusCode = options.statusCode; this.reason = options.reason; this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } -}; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 24064: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 32959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, - getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, - getUserAgentPlugin: () => getUserAgentPlugin, - resolveUserAgentConfig: () => resolveUserAgentConfig, - userAgentMiddleware: () => userAgentMiddleware -}); -module.exports = __toCommonJS(index_exports); - -// src/configurations.ts -var import_core = __nccwpck_require__(31863); -var DEFAULT_UA_APP_ID = void 0; -function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -__name(isValidUserAgentAppId, "isValidUserAgentAppId"); -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: /* @__PURE__ */ __name(async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - }, "userAgentAppId") - }); -} -__name(resolveUserAgentConfig, "resolveUserAgentConfig"); - -// src/user-agent-middleware.ts -var import_util_endpoints = __nccwpck_require__(83068); -var import_protocol_http = __nccwpck_require__(22475); - -// src/check-features.ts -var import_core2 = __nccwpck_require__(8704); -var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); - } - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); - } - } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - (0, import_core2.setFeature)(context, key, value); - } - } -} -__name(checkFeatures, "checkFeatures"); - -// src/constants.ts -var USER_AGENT = "user-agent"; -var X_AMZ_USER_AGENT = "x-amz-user-agent"; -var SPACE = " "; -var UA_NAME_SEPARATOR = "/"; -var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; -var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; -var UA_ESCAPE_CHAR = "-"; - -// src/encode-features.ts -var BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } else { - buffer += val; - } - continue; - } - break; - } - return buffer; -} -__name(encodeFeatures, "encodeFeatures"); - -// src/user-agent-middleware.ts -var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request)) { - return next(args); - } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push( - `m/${encodeFeatures( - Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) - )}` - ); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); - } - const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; - } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + this.body = options.body; } - return next({ - ...args, - request - }); -}, "userAgentMiddleware"); -var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } - return [prefix, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index) => { - switch (index) { - case 0: - return item; - case 1: - return `${acc}/${item}`; - default: - return `${acc}#${item}`; - } - }, ""); -}, "escapeUserAgent"); -var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true }; -var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, "applyToStack") -}), "getUserAgentPlugin"); + +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -64608,7 +52254,7 @@ var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ /***/ }), -/***/ 31863: +/***/ 71649: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -64633,410 +52279,170 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature + buildQueryString: () => buildQueryString }); module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(14349); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(7403); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; - } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); +var import_util_uri_escape = __nccwpck_require__(77291); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); } } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } - } - return preferredAuthOptions; -}, "resolveAuthOptions"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); - } - return map; + return parts.join("&"); } -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" -}; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(93534); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemePlugin"); - -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(22475); - -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" -}; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); - }, "applyToStack") -}), "getHttpSigningPlugin"); +0 && (0); -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; - } - cursor = cursor[step]; - } - return cursor; -}, "get"); -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(48977); +/***/ }), -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; - } - context.__smithy_context.features[feature] = value; -} -__name(setFeature, "setFeature"); +/***/ 40367: +/***/ ((module) => { -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } - } - } - static { - __name(this, "DefaultIdentityProviderConfig"); - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; - -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { - static { - __name(this, "HttpApiKeyAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); - } - return clonedRequest; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } -}; +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; - } -}; +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; - } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - return resolved; }; -}, "memoizeIdentityProvider"); +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -65045,17 +52451,37 @@ var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requi /***/ }), -/***/ 59472: +/***/ 3825: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(98832); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; + + +/***/ }), + +/***/ 2564: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) @@ -65064,262 +52490,57 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/event-streams/index.ts +// src/index.ts var index_exports = {}; -__export(index_exports, { - EventStreamSerde: () => EventStreamSerde -}); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(3825), module.exports); +__reExport(index_exports, __nccwpck_require__(54764), module.exports); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/event-streams/EventStreamSerde.ts -var import_schema = __nccwpck_require__(75987); -var import_util_utf8 = __nccwpck_require__(21194); -var EventStreamSerde = class { - /** - * Properties are injected by the HttpProtocol. - */ - constructor({ - marshaller, - serializer, - deserializer, - serdeContext, - defaultContentType - }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; - } - for await (const page of eventStream) { - yield page; - } - } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( - unionMember, - unionSchema, - event - ); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream for the end-user. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) - }; - } else { - return { - $unknown: event - }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; +0 && (0); + + + +/***/ }), + +/***/ 54764: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(98832); +const util_utf8_1 = __nccwpck_require__(73676); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error( - "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." - ); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } + else { + input = _input; } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; - } - } - }; - } - /** - * @param unionMember - member name within the structure that contains an event stream union. - * @param unionSchema - schema of the union. - * @param event - * - * @returns the event body (bytes) and event type (string). - */ - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = unionSchema.hasMemberSchema(unionMember); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(import_schema.SCHEMA.DOCUMENT, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; - } - } - } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } else { - serializer.write(eventSchema, event[unionMember]); - } - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); - } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; - } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.toBase64 = toBase64; /***/ }), -/***/ 48977: +/***/ 98832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -65332,911 +52553,1036 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString }); module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(92723); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; - -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(75987); -var import_serde = __nccwpck_require__(16705); -var import_protocol_http2 = __nccwpck_require__(22475); -var import_util_stream2 = __nccwpck_require__(92723); - -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(75987); -var import_protocol_http = __nccwpck_require__(22475); -var HttpProtocol = class { - constructor(options) { - this.options = options; - } - getRequestType() { - return import_protocol_http.HttpRequest; - } - getResponseType() { - return import_protocol_http.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; - } - } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } - } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); +var import_is_array_buffer = __nccwpck_require__(91447); +var import_buffer = __nccwpck_require__(20181); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }); + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } - /** - * Loads eventStream capability async (for chunking). - */ - async loadEventStreamCapability() { - const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(59472))); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 48686: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * @returns content-type default header value for event stream events and other documents. - */ - getDefaultContentType() { - throw new Error( - `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` - ); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(index_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - void schema; - void context; - void response; - void arg4; - void arg5; - return []; + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } - return context.eventStreamMarshaller; } -}; + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } +0 && (0); + + + +/***/ }), + +/***/ 16359: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); - } - } else { - payload = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; - } + this.reset(); + return aggregation; } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); + reset() { + this.byteArrays = []; + this.byteLength = 0; } - request.headers = headers; - request.query = query; - request.body = payload; - return request; - } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); +} +exports.ByteArrayCollector = ByteArrayCollector; + + +/***/ }), + +/***/ 95068: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 59138: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(2564); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; } - } - return; + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); } - } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); + catch (e) { + return callback(e); + } + return callback(); } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 19784: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(2564); +const stream_type_check_1 = __nccwpck_require__(89855); +const ChecksumStream_browser_1 = __nccwpck_require__(95068); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; - } - } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; + + +/***/ }), + +/***/ 57918: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(89855); +const ChecksumStream_1 = __nccwpck_require__(59138); +const createChecksumStream_browser_1 = __nccwpck_require__(19784); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } + return new ChecksumStream_1.ChecksumStream(init); +} + + +/***/ }), + +/***/ 66738: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(16359); +const createBufferedReadableStream_1 = __nccwpck_require__(38802); +const stream_type_check_1 = __nccwpck_require__(89855); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); + } + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - valueSchema, - value - ); - } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); - } - } - return nonHttpBindingMembers; - } -}; - -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(75987); -var import_protocol_http3 = __nccwpck_require__(22475); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 + downstream.push(null); }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input - }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); + return downstream; +} + + +/***/ }), + +/***/ 38802: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(16359); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest - }); + controller.close(); } - } else { - serializer.write(schema, _input); - payload = serializer.flush(); - } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject - }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } + if (chunk instanceof Uint8Array) { + return 1; } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } -}; + if (typeof chunk === "string") { + return 0; + } + return -1; +} -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(22475); -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath2; +/***/ }), + +/***/ 23927: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; }; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); + +/***/ }), + +/***/ 75469: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; } -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; - } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); + + +/***/ }), + +/***/ 15139: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(75469); +const stream_type_check_1 = __nccwpck_require__(89855); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); }); +}; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} + + +/***/ }), + +/***/ 35121: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * Brevity setter for "hostname". - */ - hn(hostname) { - this.hostname = hostname; - return this; - } - /** - * Brevity initial builder for "basepath". - */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +}); +module.exports = __toCommonJS(index_exports); + +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(2564); +var import_util_utf8 = __nccwpck_require__(73676); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); } - /** - * Brevity incremental builder for "path". - */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); } - /** - * Brevity setter for "headers". - */ - h(headers) { - this.headers = headers; - return this; + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static { + __name(this, "Uint8ArrayBlobAdapter"); } /** - * Brevity setter for "query". + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. */ - q(query) { - this.query = query; - return this; + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } } /** - * Brevity setter for "body". + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. */ - b(body) { - this.body = body; - return this; + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; } /** - * Brevity setter for "method". + * @param encoding - default 'utf-8'. + * @returns the blob as string. */ - m(method) { - this.method = method; - return this; + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); } }; -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(75987); -var import_serde2 = __nccwpck_require__(16705); -var import_util_base64 = __nccwpck_require__(5074); -var import_util_utf8 = __nccwpck_require__(21194); +// src/index.ts +__reExport(index_exports, __nccwpck_require__(59138), module.exports); +__reExport(index_exports, __nccwpck_require__(57918), module.exports); +__reExport(index_exports, __nccwpck_require__(66738), module.exports); +__reExport(index_exports, __nccwpck_require__(23927), module.exports); +__reExport(index_exports, __nccwpck_require__(15139), module.exports); +__reExport(index_exports, __nccwpck_require__(94202), module.exports); +__reExport(index_exports, __nccwpck_require__(86557), module.exports); +__reExport(index_exports, __nccwpck_require__(89855), module.exports); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(75987); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} +0 && (0); -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } - } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; - } - return data; - } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); - } -}; -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(75987); -var import_util_utf82 = __nccwpck_require__(21194); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; - } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); + +/***/ }), + +/***/ 6324: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(91338); +const util_base64_1 = __nccwpck_require__(2564); +const util_hex_encoding_1 = __nccwpck_require__(48686); +const util_utf8_1 = __nccwpck_require__(73676); +const stream_type_check_1 = __nccwpck_require__(89855); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); } - return data; - } - } - return this.codecDeserializer.read(ns, data); - } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); }; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(75987); -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(75987); -var import_serde3 = __nccwpck_require__(16705); -var import_util_base642 = __nccwpck_require__(5074); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; +/***/ }), + +/***/ 94202: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(42402); +const util_buffer_from_1 = __nccwpck_require__(98832); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(6324); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( - true - )}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; + + +/***/ }), + +/***/ 80155: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} + + +/***/ }), + +/***/ 86557: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(80155); +const stream_type_check_1 = __nccwpck_require__(89855); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} + + +/***/ }), + +/***/ 89855: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +}; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; + + +/***/ }), + +/***/ 77291: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(index_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 73676: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(98832); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; - } - return this.codecSerializer.write(ns, value); + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; - } - return this.codecSerializer.flush(); + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); } -}; + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 75987: +/***/ 75869: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -66249,799 +53595,912 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct + fromIni: () => fromIni }); module.exports = __toCommonJS(index_exports); -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); +// src/fromIni.ts + + +// src/resolveProfileData.ts + + +// src/resolveAssumeRoleCredentials.ts + + +var import_shared_ini_file_loader = __nccwpck_require__(46459); + +// src/resolveCredentialSource.ts +var import_client = __nccwpck_require__(5152); +var import_property_provider = __nccwpck_require__(78215); +var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { + const sourceProvidersMap = { + EcsContainer: /* @__PURE__ */ __name(async (options) => { + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(98605))); + const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, "EcsContainer"), + Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, "Ec2InstanceMetadata"), + Environment: /* @__PURE__ */ __name(async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(55606))); + return async () => fromEnv(options)().then(setNamedProvider); + }, "Environment") + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } else { + throw new import_property_provider.CredentialsProviderError( + `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, + { logger } + ); } - return schemaRef; -}; +}, "resolveCredentialSource"); +var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(22475); -var import_util_middleware = __nccwpck_require__(7403); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, +// src/resolveAssumeRoleCredentials.ts +var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { + return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); +}, "isAssumeRoleProfile"); +var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + } + return withSourceProfile; +}, "isAssumeRoleWithSourceProfile"); +var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + } + return withProviderProfile; +}, "isCredentialSourceProfile"); +var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(1136))); + options.roleAssumer = getDefaultRoleAssumer( { - ...config, - ...context + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region + } }, - response + options.clientPlugins ); - return { - response, - output: parsed + } + if (source_profile && source_profile in visitedProfiles) { + throw new import_property_provider.CredentialsProviderError( + `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), + { logger: options.logger } + ); + } + options.logger?.debug( + `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` + ); + const sourceCredsProvider = source_profile ? resolveProfileData( + source_profile, + profiles, + options, + { + ...visitedProfiles, + [source_profile]: true + }, + isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) + ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new import_property_provider.CredentialsProviderError( + `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, + { logger: options.logger, tryNextLink: false } + ); } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); } - throw error2; + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then( + (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") + ); } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; +}, "resolveAssumeRoleCredentials"); +var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { + return !section.role_arn && !!section.credential_source; +}, "isCredentialSourceWithoutRoleArn"); -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(7403); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; +// src/resolveProcessCredentials.ts -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSchemaSerdePlugin(config) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); +var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); +var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(75360))).then( + ({ fromProcess }) => fromProcess({ + ...options, + profile + })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) +), "resolveProcessCredentials"); + +// src/resolveSsoCredentials.ts + +var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60998))); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig + })().then((creds) => { + if (profileData.sso_session) { + return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } else { + return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); } + }); +}, "resolveSsoCredentials"); +var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); + +// src/resolveStaticCredentials.ts + +var isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); +var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, + ...profile.aws_account_id && { accountId: profile.aws_account_id } }; -} + return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); +}, "resolveStaticCredentials"); -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - } - static { - this.registries = /* @__PURE__ */ new Map(); - } - /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. - */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. - */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); - } - /** - * @param shapeId - query. - * @returns the schema. - */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); +// src/resolveWebIdentityCredentials.ts + +var isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile"); +var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(29956))).then( + ({ fromTokenFile }) => fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig + })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) +), "resolveWebIdentityCredentials"); + +// src/resolveProfileData.ts +var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); } - /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. - */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; - } - } - return void 0; + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); } - /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. - */ - find(predicate) { - return [...this.schemas.values()].find(predicate); + if (isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); } - /** - * Unloads the current TypeRegistry. - */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); + if (isWebIdentityProfile(data)) { + return resolveWebIdentityCredentials(data, options); } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; + if (isProcessProfile(data)) { + return resolveProcessCredentials(options, profileName); } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; + if (isSsoProfile(data)) { + return await resolveSsoCredentials(profileName, data, options); } -}; + throw new import_property_provider.CredentialsProviderError( + `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, + { logger: options.logger } + ); +}, "resolveProfileData"); -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - static assign(instance, values) { - const schema = Object.assign(instance, values); - TypeRegistry.for(schema.namespace).register(schema.name, schema); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; +// src/fromIni.ts +var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } -}; - -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/lis"); - } -}; -var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema -}); + }; + init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + return resolveProfileData( + (0, import_shared_ini_file_loader.getProfileName)({ + profile: _init.profile ?? callerClientConfig?.profile + }), + profiles, + init + ); +}, "fromIni"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/map"); - } -}; -var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema -}); +0 && (0); -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class _OperationSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _OperationSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/ope"); - } -}; -var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output -}); -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _StructureSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/str"); + +/***/ }), + +/***/ 78215: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); +module.exports = __toCommonJS(index_exports); -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor() { - super(...arguments); - this.symbol = _ErrorSchema.symbol; +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } static { - this.symbol = Symbol.for("@smithy/err"); + __name(this, "ProviderError"); + } + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } -}; -var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor -}); - -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 }; -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _SimpleSchema.symbol; +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } static { - this.symbol = Symbol.for("@smithy/sim"); + __name(this, "CredentialsProviderError"); } }; -var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef -}); -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. + * @override */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; - } - if (schema instanceof _NormalizedSchema) { - Object.assign(this, schema); - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; - } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; - } - this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); - } + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } static { - this.symbol = Symbol.for("@smithy/nor"); + __name(this, "TokenProviderError"); } - static [Symbol.hasInstance](lhs) { - return Schema[Symbol.hasInstance].bind(this)(lhs); +}; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref) { - if (ref instanceof _NormalizedSchema) { - return ref; - } - if (Array.isArray(ref)) { - const [ns, traits] = ref; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); - return ns; + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + throw err; } - return new _NormalizedSchema(ref); } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i++ & 1) === 1) { - traits[trait] = 1; - } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - return traits; + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - Object.assign(this, { schema: this.schema.getSchema() }); - return this.schema; - } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); } - return deref(this.schema); - } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; - } + if (isConstant) { + return resolved; } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; } - return inner instanceof ListSchema; - } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 27981: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; } - return inner instanceof MapSchema; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; - } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; - } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; - } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; - } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; - } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; - } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; + + +/***/ }), + +/***/ 68282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(27981); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 33517: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(68282); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; } - return this.getSchema() === SCHEMA.STREAMING_BLOB; + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; + + +/***/ }), + +/***/ 46459: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; - } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles +}); +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(27981), module.exports); + +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(68282), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(33517); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(20351); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { return false; } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() - }); - } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); - } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); - } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); - } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); - } - const schema = this.getSchema(); - if (typeof schema === "number") { - return this.memberFrom([63 & schema, 0], "key"); - } - return this.memberFrom([schema.keySchema, 0], "key"); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return this.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([63 & schema, 0], "member"); +), "getConfigData"); + +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(27981); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); + +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(27981); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(27981); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } else { + currentSection = sectionName; } - } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return this.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([collection.valueSchema, 0], "member"); + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; } } } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); } - /** - * @param member - to query. - * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). - */ - hasMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - return struct2.memberNames.includes(member); - } - return false; + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(31221); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); } - /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. - */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!struct2.memberNames.includes(member)) { - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); - } - const i = struct2.memberNames.indexOf(member); - const memberSchema = struct2.memberList[i]; - return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], member); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); } - /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @deprecated use (checked) structIterator instead. - * - * @returns a map of member names to member schemas (normalized). - */ - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(31221); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; } - } catch (ignored) { } - return buffer; } - /** - * @returns member name of event stream or empty string indicating none exists or this - * isn't a structure schema. - */ - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; - } - } - } - return ""; + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(33517); +var import_slurpFile3 = __nccwpck_require__(31221); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 31221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 20351: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * Creates a normalized member schema from the given schema and member name. - */ - memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); - } - return new _NormalizedSchema(memberSchema, memberName); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); + +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } - } - return "Unknown"; + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); } -}; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 16705: +/***/ 5861: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -67054,666 +54513,631 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/serde/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort + credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, + credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, + defaultProvider: () => defaultProvider }); module.exports = __toCommonJS(index_exports); -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; +// src/defaultProvider.ts +var import_credential_provider_env = __nccwpck_require__(55606); -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; +var import_shared_ini_file_loader = __nccwpck_require__(35); + +// src/remoteProvider.ts +var import_property_provider = __nccwpck_require__(22335); +var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +var remoteProvider = /* @__PURE__ */ __name(async (init) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(98605))); + return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); + }; } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init); +}, "remoteProvider"); + +// src/defaultProvider.ts +var multipleCredentialSourceWarningEmitted = false; +var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + async () => { + const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn; + warnFn( + `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +` + ); + multipleCredentialSourceWarningEmitted = true; + } + } + throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init.logger, + tryNextLink: true + }); } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return (0, import_credential_provider_env.fromEnv)(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new import_property_provider.CredentialsProviderError( + "Skipping SSO provider in default chain (inputs do not include SSO fields).", + { logger: init.logger } + ); + } + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(60998))); + return fromSSO(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(75869))); + return fromIni(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(75360))); + return fromProcess(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(29956))); + return fromTokenFile(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); + }, + async () => { + throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger + }); } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -var parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}; -var logger = { - warn: console.warn -}; + ), + credentialsTreatedAsExpired, + credentialsWillNeedRefresh +), "defaultProvider"); +var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); +var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}; -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); +0 && (0); + + + +/***/ }), + +/***/ 22335: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); + return to; }; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize +}); +module.exports = __toCommonJS(index_exports); + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - return valueInThisCentury; -}; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); + static { + __name(this, "ProviderError"); } - return input; -}; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } - return monthIdx + 1; }; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; + +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + static { + __name(this, "CredentialsProviderError"); } }; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; + static { + __name(this, "TokenProviderError"); } - return strictParseFloat32("0." + value) * 1e3; }; -var parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } } - if (idx === 0) { - return value; + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - return value.slice(idx); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 63733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; }; +exports.getHomeDir = getHomeDir; -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(12048); -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); +/***/ }), + +/***/ 51586: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(63733); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 12197: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(51586); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; } - }); - return str; + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); }; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); +exports.getSSOTokenFromFile = getSSOTokenFromFile; + + +/***/ }), + +/***/ 35: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return LazyJsonString(JSON.stringify(object)); + return to; }; -LazyJsonString.fromObject = LazyJsonString.from; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles +}); +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(63733), module.exports); -// src/submodules/serde/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(51586), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(12197); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(39831); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } } - return compoundSegments; -} +), "getConfigData"); -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - default: - } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; - } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); - } - return v.replace(/\\"/g, '"'); - }); -}; +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(63733); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(63733); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(63733); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); } - dot = 1; - continue; + } else { + currentSection = sectionName; } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } } } } - toString() { - return this.string; + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(31325); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; - } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); - if (prototypeMatch) { - return prototypeMatch; - } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { - return true; + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(31325); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } } - return prototypeMatch; + } + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(12197); +var import_slurpFile3 = __nccwpck_require__(31325); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; } }; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 83952: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 31325: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 39831: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -67737,240 +55161,233 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(index_exports); -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(22475); -var import_querystring_builder = __nccwpck_require__(82543); +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") }); } - httpHandlerConfigs() { - return this.config ?? {}; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 75360: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(5074); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromProcess: () => fromProcess +}); +module.exports = __toCommonJS(index_exports); + +// src/fromProcess.ts +var import_shared_ini_file_loader = __nccwpck_require__(23074); + +// src/resolveProcessCredentials.ts +var import_property_provider = __nccwpck_require__(41508); +var import_child_process = __nccwpck_require__(35317); +var import_util = __nccwpck_require__(39023); + +// src/getValidatedProcessCredentials.ts +var import_client = __nccwpck_require__(5152); +var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); + } + if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data.Expiration) { + const currentTime = /* @__PURE__ */ new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); } - isDone = done; } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...data.SessionToken && { sessionToken: data.SessionToken }, + ...data.Expiration && { expiration: new Date(data.Expiration) }, + ...data.CredentialScope && { credentialScope: data.CredentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}, "getValidatedProcessCredentials"); + +// src/resolveProcessCredentials.ts +var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== void 0) { + const execPromise = (0, import_util.promisify)(import_child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } catch (error) { + throw new import_property_provider.CredentialsProviderError(error.message, { logger }); } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); + } else { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + } + } else { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger + }); + } +}, "resolveProcessCredentials"); + +// src/fromProcess.ts +var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + return resolveProcessCredentials( + (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }), + profiles, + init.logger + ); +}, "fromProcess"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -67979,7 +55396,7 @@ __name(readToBase64, "readToBase64"); /***/ }), -/***/ 88245: +/***/ 41508: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -68004,10 +55421,143 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - isArrayBuffer: () => isArrayBuffer + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static { + __name(this, "ProviderError"); + } + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +}; + +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + static { + __name(this, "CredentialsProviderError"); + } +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); + } + static { + __name(this, "TokenProviderError"); + } +}; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -68016,7 +55566,85 @@ var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "func /***/ }), -/***/ 93534: +/***/ 53798: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; + + +/***/ }), + +/***/ 16335: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(53798); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 66204: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(16335); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; + + +/***/ }), + +/***/ 23074: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -68036,108 +55664,201 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(53798), module.exports); -// src/deserializerMiddleware.ts -var import_protocol_http = __nccwpck_require__(22475); -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(16335), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(66204); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(82688); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } + } +), "getConfigData"); + +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(53798); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); + +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(53798); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(53798); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); } + } else { + currentSection = sectionName; } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; } - } catch (e) { } } - throw error; } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); + return map; +}, "parseIni"); -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(16332); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(16332); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); + return merged; +}, "mergeConfigFiles"); -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(66204); +var import_slurpFile3 = __nccwpck_require__(16332); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; + } }; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: /* @__PURE__ */ __name((commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, "applyToStack") - }; -} -__name(getSerdePlugin, "getSerdePlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -68146,14 +55867,37 @@ __name(getSerdePlugin, "getSerdePlugin"); /***/ }), -/***/ 9068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 16332: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 82688: +/***/ ((module) => { -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -68168,786 +55912,368 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(index_exports); -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(22475); -var import_querystring_builder = __nccwpck_require__(82543); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") -}; - -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} -__name(writeBody, "writeBody"); +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - static { - __name(this, "NodeHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") }); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") }); } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -// src/node-http2-handler.ts +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); -var import_http22 = __nccwpck_require__(85675); +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - static { - __name(this, "NodeHttp2ConnectionPool"); - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 60998: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } - static { - __name(this, "NodeHttp2ConnectionManager"); +// src/loadSso.ts +var loadSso_exports = {}; +__export(loadSso_exports, { + GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, + SSOClient: () => import_client_sso.SSOClient +}); +var import_client_sso; +var init_loadSso = __esm({ + "src/loadSso.ts"() { + "use strict"; + import_client_sso = __nccwpck_require__(62054); } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } +}); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromSSO: () => fromSSO, + isSsoProfile: () => isSsoProfile, + validateSsoProfile: () => validateSsoProfile +}); +module.exports = __toCommonJS(index_exports); + +// src/fromSSO.ts + + + +// src/isSsoProfile.ts +var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile"); + +// src/resolveSSOCredentials.ts +var import_client = __nccwpck_require__(5152); +var import_token_providers = __nccwpck_require__(75433); +var import_property_provider = __nccwpck_require__(38430); +var import_shared_ini_file_loader = __nccwpck_require__(14876); +var SHOULD_FAIL_CREDENTIAL_CHAIN = false; +var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig, + parentClientConfig, + profile, + logger +}) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await (0, import_token_providers.fromSso)({ profile })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString() + }; + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger }); } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + } else { + try { + token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); } -}; - -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger }); } - static { - __name(this, "NodeHttp2Handler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + const { accessToken } = token; + const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); + const sso = ssoClient || new SSOClient2( + Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion + }) + ); + let ssoResp; + try { + ssoResp = await sso.send( + new GetRoleCredentialsCommand2({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken + }) + ); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger }); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + const { + roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} + } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger }); } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } -}; - -// src/stream-collector/collector.ts - -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + if (ssoSession) { + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); + } else { + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); } -}; + return credentials; +}, "resolveSSOCredentials"); -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/validateSsoProfile.ts + +var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { + const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; + if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { + throw new import_property_provider.CredentialsProviderError( + `Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join( + ", " + )} +Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, + { tryNextLink: false, logger } + ); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); + return profile; +}, "validateSsoProfile"); + +// src/fromSSO.ts +var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + if (!isSsoProfile(profile)) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger + }); + } + if (profile?.sso_session) { + const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); + const session = ssoSessions[profile.sso_session]; + const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; + if (ssoRegion && ssoRegion !== session.sso_region) { + throw new import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + profile.sso_region = session.sso_region; + profile.sso_start_url = session.sso_start_url; + } + const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile( + profile, + init.logger + ); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); + } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new import_property_provider.CredentialsProviderError( + 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', + { tryNextLink: false, logger: init.logger } + ); + } else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); +}, "fromSSO"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -68956,8 +56282,8 @@ __name(collectReadableStream, "collectReadableStream"); /***/ }), -/***/ 22475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 38430: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -68981,242 +56307,230 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(index_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = __nccwpck_require__(14349); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + static { + __name(this, "ProviderError"); } /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. + * @deprecated use new operator. */ - get() { - return this.values; + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } }; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. + * @override */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; + static { + __name(this, "CredentialsProviderError"); } +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. + * @override */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); + static { + __name(this, "TokenProviderError"); } }; -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; } - return cloned; } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 4484: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; }; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } + +/***/ }), + +/***/ 66773: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(4484); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); }; +exports.getSSOTokenFilepath = getSSOTokenFilepath; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +/***/ }), + +/***/ 26518: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(66773); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 82543: +/***/ 14876: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -69236,35 +56550,201 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - buildQueryString: () => buildQueryString + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(41617); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); +__reExport(index_exports, __nccwpck_require__(4484), module.exports); + +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(66773), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(26518); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(30650); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } + } +), "getConfigData"); + +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(4484); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); + +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(4484); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(4484); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } else { + currentSection = sectionName; } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } } - parts.push(qsEntry); } } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(67438); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(67438); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } + } + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(26518); +var import_slurpFile3 = __nccwpck_require__(67438); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; + } +}; // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -69273,7 +56753,32 @@ __name(buildQueryString, "buildQueryString"); /***/ }), -/***/ 14349: +/***/ 67438: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 30650: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -69413,33 +56918,121 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 86103: +/***/ 88079: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(87186); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); +exports.fromTokenFile = void 0; +const client_1 = __nccwpck_require__(5152); +const property_provider_1 = __nccwpck_require__(51264); +const fs_1 = __nccwpck_require__(79896); +const fromWebToken_1 = __nccwpck_require__(34453); +const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; +const ENV_ROLE_ARN = "AWS_ROLE_ARN"; +const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; +const fromTokenFile = (init = {}) => async () => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init, + webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + return credentials; }; -exports.fromBase64 = fromBase64; +exports.fromTokenFile = fromTokenFile; /***/ }), -/***/ 5074: +/***/ 34453: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromWebToken = void 0; +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(1136))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); +}; +exports.fromWebToken = fromWebToken; + + +/***/ }), + +/***/ 29956: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -69458,8 +57051,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(86103), module.exports); -__reExport(index_exports, __nccwpck_require__(22706), module.exports); +__reExport(index_exports, __nccwpck_require__(88079), module.exports); +__reExport(index_exports, __nccwpck_require__(34453), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -69468,76 +57061,168 @@ __reExport(index_exports, __nccwpck_require__(22706), module.exports); /***/ }), -/***/ 22706: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 51264: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(87186); -const util_utf8_1 = __nccwpck_require__(21194); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize +}); +module.exports = __toCommonJS(index_exports); + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static { + __name(this, "ProviderError"); + } + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +}; + +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + static { + __name(this, "CredentialsProviderError"); + } +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); + } + static { + __name(this, "TokenProviderError"); + } +}; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; } - else { - input = _input; + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 87186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(88245); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); + return resolved; + }; +}, "memoize"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -69546,8 +57231,10 @@ var fromString = /* @__PURE__ */ __name((input, encoding) => { /***/ }), -/***/ 48908: -/***/ ((module) => { +/***/ 52590: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -69571,44 +57258,43 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex + getHostHeaderPlugin: () => getHostHeaderPlugin, + hostHeaderMiddleware: () => hostHeaderMiddleware, + hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, + resolveHostHeaderConfig: () => resolveHostHeaderConfig }); module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; +var import_protocol_http = __nccwpck_require__(99252); +function resolveHostHeaderConfig(input) { + return input; } -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; +__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); +var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) host += `:${request.port}`; + request.headers["host"] = host; } - return out; -} -__name(toHex, "toHex"); + return next(args); +}, "hostHeaderMiddleware"); +var hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true +}; +var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, "applyToStack") +}), "getHostHeaderPlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -69617,7 +57303,7 @@ __name(toHex, "toHex"); /***/ }), -/***/ 7403: +/***/ 99252: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -69642,530 +57328,469 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig }); module.exports = __toCommonJS(index_exports); -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(14349); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 55849: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); } -} -exports.ByteArrayCollector = ByteArrayCollector; - - -/***/ }), - -/***/ 74010: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; - + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); -/***/ }), +// src/Field.ts +var import_types = __nccwpck_require__(51026); +var Field = class { + static { + __name(this, "Field"); + } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; -/***/ 97972: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; -"use strict"; +// src/httpRequest.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(5074); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); + return cloned; + } + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); } -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 41670: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +__name(cloneQuery, "cloneQuery"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(5074); -const stream_type_check_1 = __nccwpck_require__(73593); -const ChecksumStream_browser_1 = __nccwpck_require__(74010); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } }; -exports.createChecksumStream = createChecksumStream; - -/***/ }), - -/***/ 46912: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(73593); -const ChecksumStream_1 = __nccwpck_require__(97972); -const createChecksumStream_browser_1 = __nccwpck_require__(41670); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} /***/ }), -/***/ 95940: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 51026: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(55849); -const createBufferedReadableStream_1 = __nccwpck_require__(68940); -const stream_type_check_1 = __nccwpck_require__(73593); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; -} +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); -/***/ }), +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -/***/ 68940: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -"use strict"; +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(55849); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - return -1; -} - - -/***/ }), - -/***/ 33257: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -"use strict"; +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; -/***/ }), +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); -/***/ 5267: -/***/ ((__unused_webpack_module, exports) => { +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; -} /***/ }), -/***/ 42837: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 85242: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(5267); -const stream_type_check_1 = __nccwpck_require__(73593); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getLoggerPlugin: () => getLoggerPlugin, + loggerMiddleware: () => loggerMiddleware, + loggerMiddlewareOptions: () => loggerMiddlewareOptions +}); +module.exports = __toCommonJS(index_exports); + +// src/loggerMiddleware.ts +var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata + }); + return response; + } catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata }); + throw error; + } +}, "loggerMiddleware"); +var loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true }; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; - } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } -} +var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, "applyToStack") +}), "getLoggerPlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 92723: +/***/ 81568: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -70189,71 +57814,29 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter + getRecursionDetectionPlugin: () => getRecursionDetectionPlugin }); module.exports = __toCommonJS(index_exports); -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(5074); -var import_util_utf8 = __nccwpck_require__(21194); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { - static { - __name(this, "Uint8ArrayBlobAdapter"); - } - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); - } +// src/configuration.ts +var recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" }; +// src/getRecursionDetectionPlugin.ts +var import_recursionDetectionMiddleware = __nccwpck_require__(22521); +var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add((0, import_recursionDetectionMiddleware.recursionDetectionMiddleware)(), recursionDetectionMiddlewareOptions); + }, "applyToStack") +}), "getRecursionDetectionPlugin"); + // src/index.ts -__reExport(index_exports, __nccwpck_require__(97972), module.exports); -__reExport(index_exports, __nccwpck_require__(46912), module.exports); -__reExport(index_exports, __nccwpck_require__(95940), module.exports); -__reExport(index_exports, __nccwpck_require__(33257), module.exports); -__reExport(index_exports, __nccwpck_require__(42837), module.exports); -__reExport(index_exports, __nccwpck_require__(14048), module.exports); -__reExport(index_exports, __nccwpck_require__(60527), module.exports); -__reExport(index_exports, __nccwpck_require__(73593), module.exports); +__reExport(index_exports, __nccwpck_require__(22521), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -70262,212 +57845,48 @@ __reExport(index_exports, __nccwpck_require__(73593), module.exports); /***/ }), -/***/ 32454: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(83952); -const util_base64_1 = __nccwpck_require__(5074); -const util_hex_encoding_1 = __nccwpck_require__(48908); -const util_utf8_1 = __nccwpck_require__(21194); -const stream_type_check_1 = __nccwpck_require__(73593); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 14048: +/***/ 22521: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(9068); -const util_buffer_from_1 = __nccwpck_require__(87186); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(32454); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } +exports.recursionDetectionMiddleware = void 0; +const lambda_invoke_store_1 = __nccwpck_require__(37453); +const protocol_http_1 = __nccwpck_require__(24138); +const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; +const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; +const recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!protocol_http_1.HttpRequest.isInstance(request)) { + return next(args); } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), - -/***/ 72729: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? + TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); } - const readableStream = stream; - return readableStream.tee(); -} - - -/***/ }), - -/***/ 60527: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(72729); -const stream_type_check_1 = __nccwpck_require__(73593); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[ENV_TRACE_ID]; + const traceIdFromInvokeStore = lambda_invoke_store_1.InvokeStore.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} - - -/***/ }), - -/***/ 73593: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); + return next({ + ...args, + request, + }); }; -exports.isBlob = isBlob; +exports.recursionDetectionMiddleware = recursionDetectionMiddleware; /***/ }), -/***/ 41617: -/***/ ((module) => { +/***/ 24138: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -70484,27 +57903,240 @@ var __copyProps = (to, from, except, desc) => { if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return to; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); + +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = __nccwpck_require__(24064); +var Field = class { + static { + __name(this, "Field"); + } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; + +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; + +// src/httpRequest.ts + +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); + +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -70513,8 +58145,8 @@ var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri /***/ }), -/***/ 21194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 24064: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -70538,155 +58170,122 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(index_exports); -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(87186); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/toUtf8.ts +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8396: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8704); -const util_middleware_1 = __nccwpck_require__(99755); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 90546: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -"use strict"; +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(83068); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(69947); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; -/***/ }), +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); -/***/ 69947: -/***/ ((__unused_webpack_module, exports) => { +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; /***/ }), -/***/ 89443: +/***/ 32959: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -70710,1211 +58309,1840 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/sso-oidc/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - $Command: () => import_smithy_client6.Command, - AccessDeniedException: () => AccessDeniedException, - AuthorizationPendingException: () => AuthorizationPendingException, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, - CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - InternalServerException: () => InternalServerException, - InvalidClientException: () => InvalidClientException, - InvalidGrantException: () => InvalidGrantException, - InvalidRequestException: () => InvalidRequestException, - InvalidScopeException: () => InvalidScopeException, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SlowDownException: () => SlowDownException, - UnauthorizedClientException: () => UnauthorizedClientException, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - __Client: () => import_smithy_client2.Client + DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, + getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, + getUserAgentPlugin: () => getUserAgentPlugin, + resolveUserAgentConfig: () => resolveUserAgentConfig, + userAgentMiddleware: () => userAgentMiddleware }); module.exports = __toCommonJS(index_exports); -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_middleware_host_header = __nccwpck_require__(52590); -var import_middleware_logger = __nccwpck_require__(85242); -var import_middleware_recursion_detection = __nccwpck_require__(81568); -var import_middleware_user_agent = __nccwpck_require__(32959); -var import_config_resolver = __nccwpck_require__(39316); -var import_core = __nccwpck_require__(22743); -var import_middleware_content_length = __nccwpck_require__(47212); -var import_middleware_endpoint = __nccwpck_require__(42628); -var import_middleware_retry = __nccwpck_require__(19618); -var import_smithy_client2 = __nccwpck_require__(61411); -var import_httpAuthSchemeProvider = __nccwpck_require__(8396); - -// src/submodules/sso-oidc/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" +// src/configurations.ts +var import_core = __nccwpck_require__(31863); +var DEFAULT_UA_APP_ID = void 0; +function isValidUserAgentAppId(appId) { + if (appId === void 0) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +__name(isValidUserAgentAppId, "isValidUserAgentAppId"); +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: /* @__PURE__ */ __name(async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, "userAgentAppId") }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_runtimeConfig = __nccwpck_require__(16901); +} +__name(resolveUserAgentConfig, "resolveUserAgentConfig"); -// src/submodules/sso-oidc/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(36463); -var import_protocol_http = __nccwpck_require__(20843); -var import_smithy_client = __nccwpck_require__(61411); +// src/user-agent-middleware.ts +var import_util_endpoints = __nccwpck_require__(83068); +var import_protocol_http = __nccwpck_require__(22475); -// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); +// src/check-features.ts +var import_core2 = __nccwpck_require__(8704); +var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); + (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; + } else { + (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); + } + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + (0, import_core2.setFeature)(context, key, value); + } + } +} +__name(checkFeatures, "checkFeatures"); -// src/submodules/sso-oidc/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); +// src/constants.ts +var USER_AGENT = "user-agent"; +var X_AMZ_USER_AGENT = "x-amz-user-agent"; +var SPACE = " "; +var UA_NAME_SEPARATOR = "/"; +var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; +var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; +var UA_ESCAPE_CHAR = "-"; -// src/submodules/sso-oidc/SSOOIDCClient.ts -var SSOOIDCClient = class extends import_smithy_client2.Client { - static { - __name(this, "SSOOIDCClient"); - } - /** - * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); +// src/encode-features.ts +var BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; + } else { + buffer += val; + } + continue; + } + break; } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); + return buffer; +} +__name(encodeFeatures, "encodeFeatures"); + +// src/user-agent-middleware.ts +var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { + const { request } = args; + if (!import_protocol_http.HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push( + `m/${encodeFeatures( + Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) + )}` + ); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + } + const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); + const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; + } else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request + }); +}, "userAgentMiddleware"); +var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { + const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); } + return [prefix, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index) => { + switch (index) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); +}, "escapeUserAgent"); +var getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true }; +var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, "applyToStack") +}), "getUserAgentPlugin"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/sso-oidc/SSOOIDC.ts -var import_smithy_client7 = __nccwpck_require__(61411); +0 && (0); -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(42628); -var import_middleware_serde = __nccwpck_require__(62654); -var import_smithy_client6 = __nccwpck_require__(61411); -// src/submodules/sso-oidc/models/models_0.ts -var import_smithy_client4 = __nccwpck_require__(61411); -// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts -var import_smithy_client3 = __nccwpck_require__(61411); -var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { - static { - __name(this, "SSOOIDCServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); - } -}; +/***/ }), -// src/submodules/sso-oidc/models/models_0.ts -var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { - static { - __name(this, "AccessDeniedException"); - } - name = "AccessDeniedException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be access_denied.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { - static { - __name(this, "AuthorizationPendingException"); - } - name = "AuthorizationPendingException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * authorization_pending.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } +/***/ 31863: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenRequestFilterSensitiveLog"); -var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be expired_token.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - static { - __name(this, "InternalServerException"); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature +}); +module.exports = __toCommonJS(index_exports); + +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(14349); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(7403); + +// src/middleware-http-auth-scheme/resolveAuthOptions.ts +var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; } - name = "InternalServerException"; - $fault = "server"; - /** - *

Single error code. For this exception the value will be server_error.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } } -}; -var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { - static { - __name(this, "InvalidClientException"); + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } } - name = "InvalidClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + return preferredAuthOptions; +}, "resolveAuthOptions"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); } -}; -var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - static { - __name(this, "InvalidGrantException"); + return map; +} +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + ); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; } - name = "InvalidGrantException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_grant.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); } + return next(args); +}, "httpAuthSchemeMiddleware"); + +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" }; -var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_request.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); + +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(93534); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; -var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - static { - __name(this, "InvalidScopeException"); - } - name = "InvalidScopeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_scope.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemePlugin"); + +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(22475); + +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); + +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" }; -var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { - static { - __name(this, "SlowDownException"); +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + }, "applyToStack") +}), "getHttpSigningPlugin"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); + +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return void 0; + }, "paginateOperation"); +} +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; + } + cursor = cursor[step]; } - name = "SlowDownException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be slow_down.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; + return cursor; +}, "get"); + +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(48977); + +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +__name(setFeature, "setFeature"); + +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { /** - * @internal + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure */ - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } } -}; -var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { static { - __name(this, "UnauthorizedClientException"); + __name(this, "DefaultIdentityProviderConfig"); } - name = "UnauthorizedClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unauthorized_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); } }; -var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { + +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts + + +var HttpApiKeyAuthSigner = class { static { - __name(this, "UnsupportedGrantTypeException"); + __name(this, "HttpApiKeyAuthSigner"); } - name = "UnsupportedGrantTypeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unsupported_grant_type.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); + } + return clonedRequest; } }; -// src/submodules/sso-oidc/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(8704); -var import_core3 = __nccwpck_require__(22743); -var import_smithy_client5 = __nccwpck_require__(61411); -var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core3.requestBuilder)(input, context); - const headers = { - "content-type": "application/json" - }; - b.bp("/token"); - let body; - body = JSON.stringify( - (0, import_smithy_client5.take)(input, { - clientId: [], - clientSecret: [], - code: [], - codeVerifier: [], - deviceCode: [], - grantType: [], - redirectUri: [], - refreshToken: [], - scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") - }) - ); - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_CreateTokenCommand"); -var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client5.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client5.take)(data, { - accessToken: import_smithy_client5.expectString, - expiresIn: import_smithy_client5.expectInt32, - idToken: import_smithy_client5.expectString, - refreshToken: import_smithy_client5.expectString, - tokenType: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_CreateTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); - switch (errorCode) { - case "AccessDeniedException": - case "com.amazonaws.ssooidc#AccessDeniedException": - throw await de_AccessDeniedExceptionRes(parsedOutput, context); - case "AuthorizationPendingException": - case "com.amazonaws.ssooidc#AuthorizationPendingException": - throw await de_AuthorizationPendingExceptionRes(parsedOutput, context); - case "ExpiredTokenException": - case "com.amazonaws.ssooidc#ExpiredTokenException": - throw await de_ExpiredTokenExceptionRes(parsedOutput, context); - case "InternalServerException": - case "com.amazonaws.ssooidc#InternalServerException": - throw await de_InternalServerExceptionRes(parsedOutput, context); - case "InvalidClientException": - case "com.amazonaws.ssooidc#InvalidClientException": - throw await de_InvalidClientExceptionRes(parsedOutput, context); - case "InvalidGrantException": - case "com.amazonaws.ssooidc#InvalidGrantException": - throw await de_InvalidGrantExceptionRes(parsedOutput, context); - case "InvalidRequestException": - case "com.amazonaws.ssooidc#InvalidRequestException": - throw await de_InvalidRequestExceptionRes(parsedOutput, context); - case "InvalidScopeException": - case "com.amazonaws.ssooidc#InvalidScopeException": - throw await de_InvalidScopeExceptionRes(parsedOutput, context); - case "SlowDownException": - case "com.amazonaws.ssooidc#SlowDownException": - throw await de_SlowDownExceptionRes(parsedOutput, context); - case "UnauthorizedClientException": - case "com.amazonaws.ssooidc#UnauthorizedClientException": - throw await de_UnauthorizedClientExceptionRes(parsedOutput, context); - case "UnsupportedGrantTypeException": - case "com.amazonaws.ssooidc#UnsupportedGrantTypeException": - throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody, - errorCode - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AccessDeniedExceptionRes"); -var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AuthorizationPendingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AuthorizationPendingExceptionRes"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_ExpiredTokenExceptionRes"); -var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InternalServerExceptionRes"); -var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidClientExceptionRes"); -var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidGrantException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidGrantExceptionRes"); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidScopeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidScopeExceptionRes"); -var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new SlowDownException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_SlowDownExceptionRes"); -var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedClientExceptionRes"); -var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnsupportedGrantTypeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnsupportedGrantTypeExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { +var HttpBearerAuthSigner = class { static { - __name(this, "CreateTokenCommand"); + __name(this, "HttpBearerAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; } }; -// src/submodules/sso-oidc/SSOOIDC.ts -var commands = { - CreateTokenCommand -}; -var SSOOIDC = class extends SSOOIDCClient { +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { static { - __name(this, "SSOOIDC"); + __name(this, "NoAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + return httpRequest; } }; -(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), -/***/ 16901: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(39955)); -const core_1 = __nccwpck_require__(8704); -const util_user_agent_node_1 = __nccwpck_require__(51656); -const config_resolver_1 = __nccwpck_require__(39316); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(62021); -const node_http_handler_1 = __nccwpck_require__(82764); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(1546); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 1546: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 59472: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8704); -const core_2 = __nccwpck_require__(22743); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(60043); -const util_base64_1 = __nccwpck_require__(72722); -const util_utf8_1 = __nccwpck_require__(46090); -const httpAuthSchemeProvider_1 = __nccwpck_require__(8396); -const endpointResolver_1 = __nccwpck_require__(90546); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 63723: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -"use strict"; +// src/submodules/event-streams/index.ts +var index_exports = {}; +__export(index_exports, { + EventStreamSerde: () => EventStreamSerde +}); +module.exports = __toCommonJS(index_exports); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.STSClient = exports.__Client = void 0; -const middleware_host_header_1 = __nccwpck_require__(52590); -const middleware_logger_1 = __nccwpck_require__(85242); -const middleware_recursion_detection_1 = __nccwpck_require__(81568); -const middleware_user_agent_1 = __nccwpck_require__(32959); -const config_resolver_1 = __nccwpck_require__(39316); -const core_1 = __nccwpck_require__(22743); -const middleware_content_length_1 = __nccwpck_require__(47212); -const middleware_endpoint_1 = __nccwpck_require__(42628); -const middleware_retry_1 = __nccwpck_require__(19618); -const smithy_client_1 = __nccwpck_require__(61411); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(27851); -const EndpointParameters_1 = __nccwpck_require__(76811); -const runtimeConfig_1 = __nccwpck_require__(36578); -const runtimeExtensions_1 = __nccwpck_require__(37742); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); +// src/submodules/event-streams/EventStreamSerde.ts +var import_schema = __nccwpck_require__(75987); +var import_util_utf8 = __nccwpck_require__(21194); +var EventStreamSerde = class { + /** + * Properties are injected by the HttpProtocol. + */ + constructor({ + marshaller, + serializer, + deserializer, + serdeContext, + defaultContentType + }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + } + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType } + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body + }; + } + for await (const page of eventStream) { + yield page; + } + } + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( + unionMember, + unionSchema, + event + ); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders + }; + return { + headers, + body + }; + }); + } + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream for the end-user. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject + }; + } else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) + }; + } else { + return { + $unknown: event + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; } - destroy() { - super.destroy(); + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error( + "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." + ); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } } -} -exports.STSClient = STSClient; - - -/***/ }), - -/***/ 34532: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + } }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { + } + /** + * @param unionMember - member name within the structure that contains an event stream union. + * @param unionSchema - schema of the union. + * @param event + * + * @returns the event body (bytes) and event type (string). + */ + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = unionSchema.hasMemberSchema(unionMember); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(import_schema.SCHEMA.DOCUMENT, value); + } else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } else { + type = "long"; + } + } else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } else if (memberSchema.isStringSchema()) { + type = "string"; + } else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } else { + serializer.write(eventSchema, event[unionMember]); + } + } else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), + body, + eventType, + explicitPayloadContentType, + additionalHeaders }; + } }; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 27851: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 48977: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8704); -const util_middleware_1 = __nccwpck_require__(99755); -const STSClient_1 = __nccwpck_require__(63723); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; +// src/submodules/protocols/index.ts +var index_exports = {}; +__export(index_exports, { + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + HttpProtocol: () => HttpProtocol, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(92723); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); }; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; + +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); } -function createSmithyApiNoAuthHttpAuthOption(authParameters) { + +// src/submodules/protocols/HttpBindingProtocol.ts +var import_schema2 = __nccwpck_require__(75987); +var import_serde = __nccwpck_require__(16705); +var import_protocol_http2 = __nccwpck_require__(22475); +var import_util_stream2 = __nccwpck_require__(92723); + +// src/submodules/protocols/HttpProtocol.ts +var import_schema = __nccwpck_require__(75987); +var import_protocol_http = __nccwpck_require__(22475); +var HttpProtocol = class { + constructor(options) { + this.options = options; + } + getRequestType() { + return import_protocol_http.HttpRequest; + } + getResponseType() { + return import_protocol_http.HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + for (const [k, v] of endpoint.url.searchParams.entries()) { + if (!request.query) { + request.query = {}; + } + request.query[k] = v; + } + return request; + } else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const operationNs = import_schema.NormalizedSchema.of(operationSchema); + const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter( + ([, member]) => member.getMergedTraits().hostLabel + ); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } + } + deserializeMetadata(output) { return { - schemeId: "smithy.api#noAuth", + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; + } + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }); + } + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }); + } + /** + * Loads eventStream capability async (for chunking). + */ + async loadEventStreamCapability() { + const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(59472))); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType() + }); + } + /** + * @returns content-type default header value for event stream events and other documents. + */ + getDefaultContentType() { + throw new Error( + `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` + ); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + void schema; + void context; + void response; + void arg4; + void arg5; + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } +}; + +// src/submodules/protocols/HttpBindingProtocol.ts +var HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ..._input ?? {} + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new import_protocol_http2.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns + }); + } + } else { + payload = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace( + `{${memberName}+}`, + replacement.split("/").map(extendedEncodeURIComponent).join("/") + ); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } else { + hasNonHttpBindingMember = true; + } + } + if (hasNonHttpBindingMember && input) { + serializer.write(schema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + // We pass on the traits to the sub-schema + // because we are still in the process of serializing the map itself. + ...traits, + httpQuery: key, + httpQueryParams: void 0 + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } else { + dataObject = arg4; + } + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { + sections = (0, import_serde.splitEvery)(value, ",", 2); + } else { + sections = (0, import_serde.splitHeader)(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( + valueSchema, + value + ); + } } + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } else { + nonHttpBindingMembers.push(memberName); + } } - return options; + return nonHttpBindingMembers; + } }; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + +// src/submodules/protocols/RpcProtocol.ts +var import_schema3 = __nccwpck_require__(75987); +var import_protocol_http3 = __nccwpck_require__(22475); +var RpcProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest + }); + } + } else { + serializer.write(schema, _input); + payload = serializer.flush(); + } + } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema3.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject + }); + } else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } }; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - -/***/ }), - -/***/ 76811: -/***/ ((__unused_webpack_module, exports) => { +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http4 = __nccwpck_require__(22475); -"use strict"; +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath2; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new import_protocol_http4.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, + } + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; + } + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; + } + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; + } + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; + } }; +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var import_schema5 = __nccwpck_require__(75987); +var import_serde2 = __nccwpck_require__(16705); +var import_util_base64 = __nccwpck_require__(5074); +var import_util_utf8 = __nccwpck_require__(21194); -/***/ }), - -/***/ 59765: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// src/submodules/protocols/serde/determineTimestampFormat.ts +var import_schema4 = __nccwpck_require__(75987); +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(83068); -const util_endpoints_2 = __nccwpck_require__(79674); -const ruleset_1 = __nccwpck_require__(31670); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var FromStringShapeDeserializer = class { + constructor(settings) { + this.settings = settings; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + read(_schema, data) { + const ns = import_schema5.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); + } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); + } + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); + case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(data); + case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + switch (true) { + case ns.isNumericSchema(): + return Number(data); + case ns.isBigIntegerSchema(): + return BigInt(data); + case ns.isBigDecimalSchema(): + return new import_serde2.NumericValue(data, "bigDecimal"); + case ns.isBooleanSchema(): + return String(data).toLowerCase() === "true"; + } + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + } }; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; +// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts +var import_schema6 = __nccwpck_require__(75987); +var import_util_utf82 = __nccwpck_require__(21194); +var HttpInterceptingShapeDeserializer = class { + constructor(codecDeserializer, codecSettings) { + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema, data) { + const ns = import_schema6.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } + } + return this.codecDeserializer.read(ns, data); + } +}; -/***/ }), - -/***/ 31670: -/***/ ((__unused_webpack_module, exports) => { +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var import_schema8 = __nccwpck_require__(75987); -"use strict"; +// src/submodules/protocols/serde/ToStringShapeSerializer.ts +var import_schema7 = __nccwpck_require__(75987); +var import_serde3 = __nccwpck_require__(16705); +var import_util_base642 = __nccwpck_require__(5074); +var ToStringShapeSerializer = class { + constructor(settings) { + this.settings = settings; + this.stringBuffer = ""; + this.serdeContext = void 0; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + write(schema, value) { + const ns = import_schema7.NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error( + `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( + true + )}` + ); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: + this.stringBuffer = (0, import_serde3.dateToUtcString)(value); + break; + case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); + } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ruleSet = void 0; -const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; -const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "String" }, n = { [F]: true, "default": false, [G]: "Boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; -const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; -exports.ruleSet = _data; +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var HttpInterceptingShapeSerializer = class { + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = import_schema8.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== void 0) { + const buffer = this.buffer; + this.buffer = void 0; + return buffer; + } + return this.codecSerializer.flush(); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 1136: +/***/ 75987: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -71927,1496 +60155,1728 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/sts/index.ts +// src/submodules/schema/index.ts var index_exports = {}; __export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + list: () => list, + map: () => map, + op: () => op, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + struct: () => struct }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(63723), module.exports); -// src/submodules/sts/STS.ts -var import_smithy_client6 = __nccwpck_require__(61411); +// src/submodules/schema/deref.ts +var deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; -// src/submodules/sts/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(42628); -var import_middleware_serde = __nccwpck_require__(62654); -var import_smithy_client4 = __nccwpck_require__(61411); -var import_EndpointParameters = __nccwpck_require__(76811); +// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts +var import_protocol_http = __nccwpck_require__(22475); +var import_util_middleware = __nccwpck_require__(7403); +var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + try { + const parsed = await config.protocol.deserializeResponse( + operationSchema, + { + ...config, + ...context + }, + response + ); + return { + response, + output: parsed + }; + } catch (error2) { + Object.defineProperty(error2, "$response", { + value: response + }); + if (!("$metadata" in error2)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error2.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error2.$responseBodyText !== "undefined") { + if (error2.$response) { + error2.$response.body = error2.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error2.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { + } + } + throw error2; + } +}; +var findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; -// src/submodules/sts/models/models_0.ts -var import_smithy_client2 = __nccwpck_require__(61411); +// src/submodules/schema/middleware/schemaSerializationMiddleware.ts +var import_util_middleware2 = __nccwpck_require__(7403); +var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint + }); + return next({ + ...args, + request + }); +}; -// src/submodules/sts/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(61411); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { +// src/submodules/schema/middleware/getSchemaSerdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + } + }; +} + +// src/submodules/schema/TypeRegistry.ts +var TypeRegistry = class _TypeRegistry { + constructor(namespace, schemas = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; + } static { - __name(this, "STSServiceException"); + this.registries = /* @__PURE__ */ new Map(); + } + /** + * @param namespace - specifier. + * @returns the schema for that namespace, creating it if necessary. + */ + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); + } + /** + * Adds the given schema to a type registry with the same namespace. + * + * @param shapeId - to be registered. + * @param schema - to be registered. + */ + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = _TypeRegistry.for(this.getNamespace(shapeId)); + registry.schemas.set(qualifiedName, schema); + } + /** + * @param shapeId - query. + * @returns the schema. + */ + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + /** + * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, + * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which + * is unique per service/model. + * + * This is generated under a unique prefix that is combined with the service namespace, and this + * method is used to retrieve it. + * + * The base exception synthetic schema is used when an error is returned by a service, but we cannot + * determine what existing schema to use to deserialize it. + * + * @returns the synthetic base exception of the service namespace associated with this registry instance. + */ + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } + } + return void 0; + } + /** + * @param predicate - criterion. + * @returns a schema in this registry matching the predicate. + */ + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + /** + * Unloads the current TypeRegistry. + */ + destroy() { + _TypeRegistry.registries.delete(this.namespace); + this.schemas.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; + } +}; + +// src/submodules/schema/schemas/Schema.ts +var Schema = class { + static assign(instance, values) { + const schema = Object.assign(instance, values); + TypeRegistry.for(schema.namespace).register(schema.name, schema); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +}; + +// src/submodules/schema/schemas/ListSchema.ts +var ListSchema = class _ListSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _ListSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/lis"); + } +}; +var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema +}); + +// src/submodules/schema/schemas/MapSchema.ts +var MapSchema = class _MapSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _MapSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/map"); + } +}; +var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema +}); + +// src/submodules/schema/schemas/OperationSchema.ts +var OperationSchema = class _OperationSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _OperationSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/ope"); + } +}; +var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output +}); + +// src/submodules/schema/schemas/StructureSchema.ts +var StructureSchema = class _StructureSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _StructureSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/str"); + } +}; +var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList +}); + +// src/submodules/schema/schemas/ErrorSchema.ts +var ErrorSchema = class _ErrorSchema extends StructureSchema { + constructor() { + super(...arguments); + this.symbol = _ErrorSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/err"); + } +}; +var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor +}); + +// src/submodules/schema/schemas/sentinels.ts +var SCHEMA = { + BLOB: 21, + // 21 + STREAMING_BLOB: 42, + // 42 + BOOLEAN: 2, + // 2 + STRING: 0, + // 0 + NUMERIC: 1, + // 1 + BIG_INTEGER: 17, + // 17 + BIG_DECIMAL: 19, + // 19 + DOCUMENT: 15, + // 15 + TIMESTAMP_DEFAULT: 4, + // 4 + TIMESTAMP_DATE_TIME: 5, + // 5 + TIMESTAMP_HTTP_DATE: 6, + // 6 + TIMESTAMP_EPOCH_SECONDS: 7, + // 7 + LIST_MODIFIER: 64, + // 64 + MAP_MODIFIER: 128 + // 128 +}; + +// src/submodules/schema/schemas/SimpleSchema.ts +var SimpleSchema = class _SimpleSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _SimpleSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/sim"); + } +}; +var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef +}); + +// src/submodules/schema/schemas/NormalizedSchema.ts +var NormalizedSchema = class _NormalizedSchema { + /** + * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. + * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. + */ + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + this.symbol = _NormalizedSchema.symbol; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema instanceof _NormalizedSchema) { + Object.assign(this, schema); + this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static { + this.symbol = Symbol.for("@smithy/nor"); + } + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); + } + /** + * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. + */ + static of(ref) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + if (Array.isArray(ref)) { + const [ns, traits] = ref; + if (ns instanceof _NormalizedSchema) { + Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + return new _NormalizedSchema(ref); + } + /** + * @param indicator - numeric indicator for preset trait combination. + * @returns equivalent trait object. + */ + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i++ & 1) === 1) { + traits[trait] = 1; + } + } + return traits; } /** - * @internal + * @returns the underlying non-normalized schema. */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; - -// src/submodules/sts/models/models_0.ts -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + Object.assign(this, { schema: this.schema.getSchema() }); + return this.schema; + } + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); + } + return deref(this.schema); } - name = "ExpiredTokenException"; - $fault = "client"; /** - * @internal + * @param withNamespace - qualifies the name. + * @returns e.g. `MyShape` or `com.namespace#MyShape`. */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; + } + } + return this.name || void 0; } - name = "MalformedPolicyDocumentException"; - $fault = "client"; /** - * @internal + * @returns the member name if the schema is a member schema. + * @throws Error when the schema isn't a member schema. */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + } + return this.memberName; } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); + isMemberSchema() { + return this._isMemberSchema; + } + isUnitSchema() { + return this.getSchema() === "unit"; } - name = "PackedPolicyTooLargeException"; - $fault = "client"; /** - * @internal + * boolean methods on this class help control flow in shape serialization and deserialization. */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + } + return inner instanceof ListSchema; } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + } + return inner instanceof MapSchema; + } + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; + } + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isTimestampSchema() { + const schema = this.getSchema(); + return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; + } + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; + } + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; + } + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; + } + return this.getSchema() === SCHEMA.STREAMING_BLOB; } - name = "RegionDisabledException"; - $fault = "client"; /** - * @internal + * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. + * @returns whether the schema has the idempotencyToken trait. */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } -}; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); + isIdempotencyToken() { + if (typeof this.traits === "number") { + return (this.traits & 4) === 4; + } else if (typeof this.traits === "object") { + return !!this.traits.idempotencyToken; + } + return false; } - name = "IDPRejectedClaimException"; - $fault = "client"; /** - * @internal + * @returns own traits merged with member traits, where member traits of the same trait key take priority. + * This method is cached. */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } -}; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); } - name = "InvalidIdentityTokenException"; - $fault = "client"; /** - * @internal + * @returns only the member traits. If the schema is not a member, this returns empty. */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); } -}; -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); + /** + * @returns only the traits inherent to the shape or member target shape if this schema is a member. + * If there are any member traits they are excluded. + */ + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); } - name = "IDPCommunicationErrorException"; - $fault = "client"; /** - * @internal + * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map or Document. */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); + getKeySchema() { + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); + } + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + if (typeof schema === "number") { + return this.memberFrom([63 & schema, 0], "key"); + } + return this.memberFrom([schema.keySchema, 0], "key"); } -}; - -// src/submodules/sts/protocols/Aws_query.ts -var import_core = __nccwpck_require__(8704); -var import_protocol_http = __nccwpck_require__(20843); -var import_smithy_client3 = __nccwpck_require__(61411); -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); + /** + * @returns the schema of the map's value or list's member. + * Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map, List, nor Document. + */ + getValueSchema() { + const schema = this.getSchema(); + if (typeof schema === "number") { + if (this.isMapSchema()) { + return this.memberFrom([63 & schema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([63 & schema, 0], "member"); + } + } + if (schema && typeof schema === "object") { + if (this.isStructSchema()) { + throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + } + const collection = schema; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return this.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([collection.valueSchema, 0], "member"); + } + } + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); + /** + * @param member - to query. + * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). + */ + hasMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + return struct2.memberNames.includes(member); + } + return false; } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(output.body, context) - }; - const errorCode = loadQueryErrorCode(output, parsedOutput.body); - switch (errorCode) { - case "ExpiredTokenException": - case "com.amazonaws.sts#ExpiredTokenException": - throw await de_ExpiredTokenExceptionRes(parsedOutput, context); - case "MalformedPolicyDocument": - case "com.amazonaws.sts#MalformedPolicyDocumentException": - throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); - case "PackedPolicyTooLarge": - case "com.amazonaws.sts#PackedPolicyTooLargeException": - throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); - case "RegionDisabledException": - case "com.amazonaws.sts#RegionDisabledException": - throw await de_RegionDisabledExceptionRes(parsedOutput, context); - case "IDPCommunicationError": - case "com.amazonaws.sts#IDPCommunicationErrorException": - throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); - case "IDPRejectedClaim": - case "com.amazonaws.sts#IDPRejectedClaimException": - throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context); - case "InvalidIdentityToken": - case "com.amazonaws.sts#InvalidIdentityTokenException": - throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody: parsedBody.Error, - errorCode - }); + /** + * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` + * and will have the member name given. + * @param member - which member to retrieve and wrap. + * + * @throws Error if member does not exist or the schema is neither a document nor structure. + * Note that errors are assumed to be structures and unions are considered structures for these purposes. + */ + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + if (!struct2.memberNames.includes(member)) { + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); + } + const i = struct2.memberNames.indexOf(member); + const memberSchema = struct2.memberList[i]; + return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; + /** + * This can be used for checking the members as a hashmap. + * Prefer the structIterator method for iteration. + * + * This does NOT return list and map members, it is only for structures. + * + * @deprecated use (checked) structIterator instead. + * + * @returns a map of member names to member schemas (normalized). + */ + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } catch (ignored) { + } + return buffer; } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; + /** + * @returns member name of event stream or empty string indicating none exists or this + * isn't a structure schema. + */ + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; + /** + * Allows iteration over members of a structure schema. + * Each yield is a pair of the member name and member schema. + * + * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). + */ + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct2 = this.getSchema(); + for (let i = 0; i < struct2.memberNames.length; ++i) { + yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; + /** + * Creates a normalized member schema from the given schema and member name. + */ + memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); + return new _NormalizedSchema(memberSchema, memberName); } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; + /** + * @returns a last-resort human-readable name for the schema if it has no other identifiers. + */ + getSchemaName() { + const schema = this.getSchema(); + if (typeof schema === "number") { + const _schema = 63 & schema; + const container = 192 & schema; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; + } } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; + return "Unknown"; } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 16705: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/serde/index.ts +var index_exports = {}; +__export(index_exports, { + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger, + nv: () => nv, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/serde/copyDocumentWithTransform.ts +var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; + +// src/submodules/serde/parse-utils.ts +var parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; +}; +var expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; + if (value === 0) { + return false; } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + if (value === 1) { + return true; } - const memberEntries = se_PolicyDescriptorType(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; - } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - const memberEntries = se_ProvidedContext(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; - } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; - } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + if (lower === "false") { + return false; } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + if (lower === "true") { + return true; } - const memberEntries = se_Tag(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; } - return entries; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + if (typeof value === "boolean") { + return value; } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +var expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); + if (typeof value === "number") { + return value; } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + return expected; +}; +var expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +var expectInt = expectLong; +var expectInt32 = (value) => expectSizedInt(value, 32); +var expectShort = (value) => expectSizedInt(value, 16); +var expectByte = (value) => expectSizedInt(value, 8); +var expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); + return expected; +}; +var castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); +}; +var expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); + return value; +}; +var expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); + if (typeof value === "object" && !Array.isArray(value)) { + return value; } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +var expectString = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); + if (typeof value === "string") { + return value; } - return contents; -}, "de_Credentials"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); } - return contents; -}, "de_ExpiredTokenException"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +var expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + return asObject; +}; +var strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + return expectNumber(value); +}; +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + return expectFloat32(value); +}; +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers - }; - if (resolvedHostname !== void 0) { - contents.hostname = resolvedHostname; + return parseFloat(value); +}; +var limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); } - if (body !== void 0) { - contents.body = body; + return expectNumber(value); +}; +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" + return expectFloat32(value); }; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _K = "Key"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _SAK = "SecretAccessKey"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TTK = "TransitiveTagKeys"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; +var parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); } - if (output.statusCode == 404) { - return "NotFound"; +}; +var strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); } -}, "loadQueryErrorCode"); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); + return expectLong(value); +}; +var strictParseInt = strictParseLong; +var strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); } + return expectInt32(value); }; - -// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(42628); -var import_middleware_serde2 = __nccwpck_require__(62654); -var import_smithy_client5 = __nccwpck_require__(61411); -var import_EndpointParameters2 = __nccwpck_require__(76811); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { - static { - __name(this, "AssumeRoleWithWebIdentityCommand"); +var strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +var strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); } + return expectByte(value); +}; +var stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}; +var logger = { + warn: console.warn }; -// src/submodules/sts/STS.ts -var import_STSClient = __nccwpck_require__(63723); -var commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand +// src/submodules/serde/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } + return date; }; -(0, import_smithy_client6.createAggregatedClient)(commands, STS); - -// src/submodules/sts/index.ts -var import_EndpointParameters3 = __nccwpck_require__(76811); - -// src/submodules/sts/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(5152); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/submodules/sts/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(63723); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 36578: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const tslib_1 = __nccwpck_require__(61860); -const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(39955)); -const core_1 = __nccwpck_require__(8704); -const util_user_agent_node_1 = __nccwpck_require__(51656); -const config_resolver_1 = __nccwpck_require__(39316); -const core_2 = __nccwpck_require__(22743); -const hash_node_1 = __nccwpck_require__(5092); -const middleware_retry_1 = __nccwpck_require__(19618); -const node_config_provider_1 = __nccwpck_require__(62021); -const node_http_handler_1 = __nccwpck_require__(82764); -const util_body_length_node_1 = __nccwpck_require__(13638); -const util_retry_1 = __nccwpck_require__(15518); -const runtimeConfig_shared_1 = __nccwpck_require__(24443); -const smithy_client_1 = __nccwpck_require__(61411); -const util_defaults_mode_node_1 = __nccwpck_require__(15435); -const smithy_client_2 = __nccwpck_require__(61411); -const getRuntimeConfig = (config) => { - (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); - (0, core_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? - (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, - }, config), - sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) + ); + } + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + throw new TypeError("Invalid RFC-7231 date-time value"); }; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 24443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8704); -const core_2 = __nccwpck_require__(22743); -const smithy_client_1 = __nccwpck_require__(61411); -const url_parser_1 = __nccwpck_require__(60043); -const util_base64_1 = __nccwpck_require__(72722); -const util_utf8_1 = __nccwpck_require__(46090); -const httpAuthSchemeProvider_1 = __nccwpck_require__(27851); -const endpointResolver_1 = __nccwpck_require__(59765); -const getRuntimeConfig = (config) => { - return { - apiVersion: "2011-06-15", - base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "STS", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; +var parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); }; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 37742: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveRuntimeExtensions = void 0; -const region_config_resolver_1 = __nccwpck_require__(36463); -const protocol_http_1 = __nccwpck_require__(20843); -const smithy_client_1 = __nccwpck_require__(61411); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(34532); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +var buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); }; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; - - -/***/ }), - -/***/ 22743: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +var parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); } - return to; + return input; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(65165); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(99755); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; +var parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } - } + return monthIdx + 1; +}; +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } - return preferredAuthOptions; -}, "resolveAuthOptions"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); +}; +var isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +var parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } - return map; -} -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; + return dateVal; +}; +var parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); + return strictParseFloat32("0." + value) * 1e3; +}; +var parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; }; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(62654); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +var stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); }; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); - }, "applyToStack") -}), "getHttpAuthSchemePlugin"); -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(20843); +// src/submodules/serde/generateIdempotencyToken.ts +var import_uuid = __nccwpck_require__(12048); -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); +// src/submodules/serde/lazy-json.ts +var LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + } + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); - -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" + return LazyJsonString(JSON.stringify(object)); }; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); - }, "applyToStack") -}), "getHttpSigningPlugin"); +LazyJsonString.fromObject = LazyJsonString.from; -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); +// src/submodules/serde/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); +// src/submodules/serde/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } else { + currentSegment += delimiter + segments[i]; } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } - cursor = cursor[step]; } - return cursor; -}, "get"); - -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(14097); - -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; + if (currentSegment !== "") { + compoundSegments.push(currentSegment); } - context.__smithy_context.features[feature] = value; + return compoundSegments; } -__name(setFeature, "setFeature"); -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); +// src/submodules/serde/split-header.ts +var splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + default: + } + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; + } + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +// src/submodules/serde/value/NumericValue.ts +var NumericValue = class _NumericValue { + constructor(string, type) { + this.string = string; + this.type = type; + let dot = 0; + for (let i = 0; i < string.length; ++i) { + const char = string.charCodeAt(i); + if (i === 0 && char === 45) { + continue; + } + if (char === 46) { + if (dot) { + throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); + } + dot = 1; + continue; + } + if (char < 48 || char > 57) { + throw new Error( + `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` + ); } } } - static { - __name(this, "DefaultIdentityProviderConfig"); + toString() { + return this.string; } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); + if (prototypeMatch) { + return prototypeMatch; + } + if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { + return true; + } + return prototypeMatch; } }; +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts +/***/ }), + +/***/ 83952: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var HttpApiKeyAuthSigner = class { +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(index_exports); + +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(22475); +var import_querystring_builder = __nccwpck_require__(82543); + +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { static { - __name(this, "HttpApiKeyAuthSigner"); + __name(this, "FetchHttpHandler"); } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") ); } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) ); } - return clonedRequest; + return Promise.race(raceOfPromises).finally(removeSignalEventListener); } -}; - -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts - -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; + httpHandlerConfigs() { + return this.config ?? {}; } }; -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(5074); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; } -}; - -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); } - return resolved; + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; - } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; - } - return resolved; - }; -}, "memoizeIdentityProvider"); + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -73425,13 +61885,14 @@ var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requi /***/ }), -/***/ 74992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 88245: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -73446,252 +61907,152 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/event-streams/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - EventStreamSerde: () => EventStreamSerde + isArrayBuffer: () => isArrayBuffer }); module.exports = __toCommonJS(index_exports); - -// src/submodules/event-streams/EventStreamSerde.ts -var import_schema = __nccwpck_require__(67635); -var import_util_utf8 = __nccwpck_require__(46090); -var EventStreamSerde = class { - /** - * Properties are injected by the HttpProtocol. - */ - constructor({ - marshaller, - serializer, - deserializer, - serdeContext, - defaultContentType - }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; - } - for await (const page of eventStream) { - yield page; - } - } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( - unionMember, - unionSchema, - event - ); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); - } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream for the end-user. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) - }; - } else { - return { - $unknown: event - }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; - } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error( - "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." - ); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } - } +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 93534: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption +}); +module.exports = __toCommonJS(index_exports); + +// src/deserializerMiddleware.ts +var import_protocol_http = __nccwpck_require__(22475); +var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); } } - }; - } - /** - * @param unionMember - member name within the structure that contains an event stream union. - * @param unionSchema - schema of the union. - * @param event - * - * @returns the event body (bytes) and event type (string). - */ - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = unionSchema.hasMemberSchema(unionMember); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(import_schema.SCHEMA.DOCUMENT, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; - } - } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } else { - serializer.write(eventSchema, event[unionMember]); + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; } - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } catch (e) { } } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; + throw error; + } +}, "deserializerMiddleware"); +var findHeader = /* @__PURE__ */ __name((pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}, "findHeader"); + +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); + +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true }; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: /* @__PURE__ */ __name((commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, "applyToStack") + }; +} +__name(getSerdePlugin, "getSerdePlugin"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 14097: +/***/ 9068: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __create = Object.create; @@ -73700,6 +62061,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -73722,901 +62084,1331 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(64691); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(22475); +var import_querystring_builder = __nccwpck_require__(82543); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(67635); -var import_serde = __nccwpck_require__(65409); -var import_protocol_http2 = __nccwpck_require__(20843); -var import_util_stream2 = __nccwpck_require__(64691); +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(67635); -var import_protocol_http = __nccwpck_require__(20843); -var HttpProtocol = class { - constructor(options) { - this.options = options; +// src/timing.ts +var timing = { + setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), + clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; } - getRequestType() { - return import_protocol_http.HttpRequest; + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; } - getResponseType() { - return import_protocol_http.HttpResponse; + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; + request.setTimeout(timeout, onTimeout); } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; + if (sendBody) { + writeBody(httpRequest, request.body); } - /** - * @param eventStream - the iterable provided by the caller. - * @param requestSchema - the schema of the event stream container (struct). - * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). - * - * @returns a stream suitable for the HTTP body of a request. - */ - async serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; } - /** - * @param response - http response from which to read the event stream. - * @param unionSchema - schema of the event stream container (struct). - * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). - * - * @returns the asyncIterable of the event stream. - */ - async deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } }); } + static { + __name(this, "NodeHttpHandler"); + } /** - * Loads eventStream capability async (for chunking). + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. */ - async loadEventStreamCapability() { - const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(74992))); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); } /** - * @returns content-type default header value for event stream events and other documents. + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. */ - getDefaultContentType() { - throw new Error( - `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` - ); - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - void schema; - void context; - void response; - void arg4; - void arg5; - return []; - } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; } - return context.eventStreamMarshaller; - } -}; - -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); } } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); - } - } else { - payload = inputMemberValue; - } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + reject(err); } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/node-http2-handler.ts + + +var import_http22 = __nccwpck_require__(85675); + +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); + +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; + } + static { + __name(this, "NodeHttp2ConnectionPool"); + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); } } - return; } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); - } - } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); + } +}; + +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); } } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); + static { + __name(this, "NodeHttp2ConnectionManager"); + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); } - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; + }); } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - valueSchema, - value - ); - } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; + } + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); + connectionPool.remove(session); } + this.sessionCache.delete(key); } - return nonHttpBindingMembers; + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); } }; -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(67635); -var import_protocol_http3 = __nccwpck_require__(20843); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input - }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); - } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest - }); - } +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); } else { - serializer.write(schema, _input); - payload = serializer.flush(); + resolve(options || {}); } + }); + } + static { + __name(this, "NodeHttp2Handler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; + return new _NodeHttp2Handler(instanceOrOptions); } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; } }; -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(20843); +// src/stream-collector/collector.ts -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + static { + __name(this, "Collector"); + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); } - return resolvedPath2; }; -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; } -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; +__name(collectReadableStream, "collectReadableStream"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 22475: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); + +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = __nccwpck_require__(14349); +var Field = class { + static { + __name(this, "Field"); + } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; + +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); } /** - * Brevity setter for "hostname". + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. */ - hn(hostname) { - this.hostname = hostname; - return this; + setField(field) { + this.entries[field.name.toLowerCase()] = field; } /** - * Brevity initial builder for "basepath". + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; + getField(name) { + return this.entries[name.toLowerCase()]; } /** - * Brevity incremental builder for "path". + * Delete entry from collection. + * + * @param name Name of the entry to delete. */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + removeField(name) { + delete this.entries[name.toLowerCase()]; } /** - * Brevity setter for "headers". + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. */ - h(headers) { - this.headers = headers; - return this; + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; + +// src/httpRequest.ts + +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; } /** - * Brevity setter for "query". + * Note: this does not deep-clone the body. */ - q(query) { - this.query = query; - return this; + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; } /** - * Brevity setter for "body". + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. */ - b(body) { - this.body = body; - return this; + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } /** - * Brevity setter for "method". + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). */ - m(method) { - this.method = method; - return this; + clone() { + return _HttpRequest.clone(this); } }; - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(67635); -var import_serde2 = __nccwpck_require__(65409); -var import_util_base64 = __nccwpck_require__(72722); -var import_util_utf8 = __nccwpck_require__(46090); - -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(67635); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); } +__name(cloneQuery, "cloneQuery"); -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } - } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; - } - return data; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(67635); -var import_util_utf82 = __nccwpck_require__(46090); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 82543: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(index_exports); +var import_util_uri_escape = __nccwpck_require__(41617); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); } - return this.codecDeserializer.read(ns, data); } + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 14349: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(67635); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(67635); -var import_serde3 = __nccwpck_require__(65409); -var import_util_base642 = __nccwpck_require__(72722); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") + }); } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( - true - )}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; - } -}; + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 86103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(87186); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); } - return this.codecSerializer.flush(); + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; + + +/***/ }), + +/***/ 5074: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(86103), module.exports); +__reExport(index_exports, __nccwpck_require__(22706), module.exports); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 67635: +/***/ 22706: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(87186); +const util_utf8_1 = __nccwpck_require__(21194); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; + + +/***/ }), + +/***/ 87186: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -74631,797 +63423,1010 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString }); module.exports = __toCommonJS(index_exports); - -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); +var import_is_array_buffer = __nccwpck_require__(88245); +var import_buffer = __nccwpck_require__(20181); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } - return schemaRef; -}; - -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(20843); -var import_util_middleware = __nccwpck_require__(99755); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, - { - ...config, - ...context - }, - response - ); - return { - response, - output: parsed - }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { - } - } - throw error2; + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(99755); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; +0 && (0); -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSchemaSerdePlugin(config) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - } - }; -} -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - } - static { - this.registries = /* @__PURE__ */ new Map(); - } - /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. - */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. - */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); - } - /** - * @param shapeId - query. - * @returns the schema. - */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. - */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; - } - } - return void 0; - } - /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. - */ - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - /** - * Unloads the current TypeRegistry. - */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; - } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; - } -}; -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - static assign(instance, values) { - const schema = Object.assign(instance, values); - TypeRegistry.for(schema.namespace).register(schema.name, schema); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; - } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } -}; +/***/ }), -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/lis"); - } -}; -var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema -}); +/***/ 48908: +/***/ ((module) => { -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/map"); - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema -}); - -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class _OperationSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _OperationSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/ope"); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output -}); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _StructureSchema.symbol; +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(index_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; } - static { - this.symbol = Symbol.for("@smithy/str"); + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); } -}; -var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList -}); - -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor() { - super(...arguments); - this.symbol = _ErrorSchema.symbol; + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } } - static { - this.symbol = Symbol.for("@smithy/err"); + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; } -}; -var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor -}); + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 -}; -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor() { - super(...arguments); - this.symbol = _SimpleSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/sim"); +/***/ }), + +/***/ 7403: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider }); +module.exports = __toCommonJS(index_exports); -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { - /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. - */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(14349); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 55849: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; } - if (schema instanceof _NormalizedSchema) { - Object.assign(this, schema); - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; } - this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + reset() { + this.byteArrays = []; + this.byteLength = 0; } - } - static { - this.symbol = Symbol.for("@smithy/nor"); - } - static [Symbol.hasInstance](lhs) { - return Schema[Symbol.hasInstance].bind(this)(lhs); - } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref) { - if (ref instanceof _NormalizedSchema) { - return ref; +} +exports.ByteArrayCollector = ByteArrayCollector; + + +/***/ }), + +/***/ 74010: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 97972: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(5074); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); } - if (Array.isArray(ref)) { - const [ns, traits] = ref; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); - return ns; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); } - return new _NormalizedSchema(ref); - } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i++ & 1) === 1) { - traits[trait] = 1; - } +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 41670: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(5074); +const stream_type_check_1 = __nccwpck_require__(73593); +const ChecksumStream_browser_1 = __nccwpck_require__(74010); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } - return traits; - } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - Object.assign(this, { schema: this.schema.getSchema() }); - return this.schema; + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; + + +/***/ }), + +/***/ 46912: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(73593); +const ChecksumStream_1 = __nccwpck_require__(97972); +const createChecksumStream_browser_1 = __nccwpck_require__(41670); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); } - return deref(this.schema); - } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; - } + return new ChecksumStream_1.ChecksumStream(init); +} + + +/***/ }), + +/***/ 95940: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(55849); +const createBufferedReadableStream_1 = __nccwpck_require__(68940); +const stream_type_check_1 = __nccwpck_require__(73593); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} + + +/***/ }), + +/***/ 68940: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(55849); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); } - return inner instanceof ListSchema; - } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; } - return inner instanceof MapSchema; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; - } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; - } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; - } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; - } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; - } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; - } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; + if (chunk instanceof Uint8Array) { + return 1; } - return this.getSchema() === SCHEMA.STREAMING_BLOB; - } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; + if (typeof chunk === "string") { + return 0; } - return false; - } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() + return -1; +} + + +/***/ }), + +/***/ 33257: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); }); - } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); - } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); - } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +}; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; + + +/***/ }), + +/***/ 5267: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; } - const schema = this.getSchema(); - if (typeof schema === "number") { - return this.memberFrom([63 & schema, 0], "key"); + return collected; +} + + +/***/ }), + +/***/ 42837: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(5267); +const stream_type_check_1 = __nccwpck_require__(73593); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); } - return this.memberFrom([schema.keySchema, 0], "key"); - } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return this.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([63 & schema, 0], "member"); - } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); +}; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); - } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return this.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return this.memberFrom([collection.valueSchema, 0], "member"); + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); } - } - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); + callback(); } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); +} + + +/***/ }), + +/***/ 92723: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * @param member - to query. - * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). - */ - hasMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - return struct2.memberNames.includes(member); - } - return false; + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +}); +module.exports = __toCommonJS(index_exports); + +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(5074); +var import_util_utf8 = __nccwpck_require__(21194); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); + } + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); + } + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static { + __name(this, "Uint8ArrayBlobAdapter"); } /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!struct2.memberNames.includes(member)) { - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); - } - const i = struct2.memberNames.indexOf(member); - const memberSchema = struct2.memberList[i]; - return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); - } - if (this.isDocumentSchema()) { - return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); } /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @deprecated use (checked) structIterator instead. - * - * @returns a map of member names to member schemas (normalized). + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. */ - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; - } - } catch (ignored) { - } - return buffer; + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; } /** - * @returns member name of event stream or empty string indicating none exists or this - * isn't a structure schema. + * @param encoding - default 'utf-8'. + * @returns the blob as string. */ - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } +}; + +// src/index.ts +__reExport(index_exports, __nccwpck_require__(97972), module.exports); +__reExport(index_exports, __nccwpck_require__(46912), module.exports); +__reExport(index_exports, __nccwpck_require__(95940), module.exports); +__reExport(index_exports, __nccwpck_require__(33257), module.exports); +__reExport(index_exports, __nccwpck_require__(42837), module.exports); +__reExport(index_exports, __nccwpck_require__(14048), module.exports); +__reExport(index_exports, __nccwpck_require__(60527), module.exports); +__reExport(index_exports, __nccwpck_require__(73593), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 32454: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(83952); +const util_base64_1 = __nccwpck_require__(5074); +const util_hex_encoding_1 = __nccwpck_require__(48908); +const util_utf8_1 = __nccwpck_require__(21194); +const stream_type_check_1 = __nccwpck_require__(73593); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; + + +/***/ }), + +/***/ 14048: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(9068); +const util_buffer_from_1 = __nccwpck_require__(87186); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(32454); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } - } - } - return ""; - } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); - } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } - } - /** - * Creates a normalized member schema from the given schema and member name. - */ - memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; + + +/***/ }), + +/***/ 72729: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); } - return new _NormalizedSchema(memberSchema, memberName); - } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } + const readableStream = stream; + return readableStream.tee(); +} + + +/***/ }), + +/***/ 60527: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(72729); +const stream_type_check_1 = __nccwpck_require__(73593); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); } - return "Unknown"; + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} + + +/***/ }), + +/***/ 73593: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +}; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; + + +/***/ }), + +/***/ 41617: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(index_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 65409: +/***/ 21194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -75436,1572 +64441,1384 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/serde/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 }); module.exports = __toCommonJS(index_exports); -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(87186); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); - } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -var parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; } - return expectInt32(value); -}; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); } - return expectShort(value); + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 8396: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(8704); +const util_middleware_1 = __nccwpck_require__(99755); +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; }; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); +exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; }; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); }; -var logger = { - warn: console.warn +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 90546: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(83068); +const util_endpoints_2 = __nccwpck_require__(79674); +const ruleset_1 = __nccwpck_require__(69947); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); }; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + +/***/ }), + +/***/ 69947: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ruleSet = void 0; +const u = "required", v = "fn", w = "argv", x = "ref"; +const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; +const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; + + +/***/ }), + +/***/ 89443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return date; + return to; }; -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/sso-oidc/index.ts +var index_exports = {}; +__export(index_exports, { + $Command: () => import_smithy_client6.Command, + AccessDeniedException: () => AccessDeniedException, + AuthorizationPendingException: () => AuthorizationPendingException, + CreateTokenCommand: () => CreateTokenCommand, + CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, + CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + InternalServerException: () => InternalServerException, + InvalidClientException: () => InvalidClientException, + InvalidGrantException: () => InvalidGrantException, + InvalidRequestException: () => InvalidRequestException, + InvalidScopeException: () => InvalidScopeException, + SSOOIDC: () => SSOOIDC, + SSOOIDCClient: () => SSOOIDCClient, + SSOOIDCServiceException: () => SSOOIDCServiceException, + SlowDownException: () => SlowDownException, + UnauthorizedClientException: () => UnauthorizedClientException, + UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, + __Client: () => import_smithy_client2.Client +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_middleware_host_header = __nccwpck_require__(52590); +var import_middleware_logger = __nccwpck_require__(85242); +var import_middleware_recursion_detection = __nccwpck_require__(81568); +var import_middleware_user_agent = __nccwpck_require__(32959); +var import_config_resolver = __nccwpck_require__(39316); +var import_core = __nccwpck_require__(22743); +var import_middleware_content_length = __nccwpck_require__(47212); +var import_middleware_endpoint = __nccwpck_require__(42628); +var import_middleware_retry = __nccwpck_require__(19618); +var import_smithy_client2 = __nccwpck_require__(61411); +var import_httpAuthSchemeProvider = __nccwpck_require__(8396); + +// src/submodules/sso-oidc/endpoint/EndpointParameters.ts +var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth" + }); +}, "resolveClientEndpointParameters"); +var commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +}; + +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_runtimeConfig = __nccwpck_require__(16901); + +// src/submodules/sso-oidc/runtimeExtensions.ts +var import_region_config_resolver = __nccwpck_require__(36463); +var import_protocol_http = __nccwpck_require__(20843); +var import_smithy_client = __nccwpck_require__(61411); + +// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts +var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; +}, "getHttpAuthExtensionConfiguration"); +var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}, "resolveHttpAuthRuntimeConfig"); + +// src/submodules/sso-oidc/runtimeExtensions.ts +var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign( + (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), + (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), + (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), + getHttpAuthExtensionConfiguration(runtimeConfig) + ); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign( + runtimeConfig, + (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), + (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), + (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), + resolveHttpAuthRuntimeConfig(extensionConfiguration) + ); +}, "resolveRuntimeExtensions"); + +// src/submodules/sso-oidc/SSOOIDCClient.ts +var SSOOIDCClient = class extends import_smithy_client2.Client { + static { + __name(this, "SSOOIDCClient"); } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds + /** + * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. + */ + config; + constructor(...[configuration]) { + const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use( + (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }), "identityProviderConfigProvider") }) ); + this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); -}; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; + /** + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. + */ + destroy() { + super.destroy(); } - return valueInThisCentury; }; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); + +// src/submodules/sso-oidc/SSOOIDC.ts +var import_smithy_client7 = __nccwpck_require__(61411); + +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(42628); +var import_middleware_serde = __nccwpck_require__(62654); +var import_smithy_client6 = __nccwpck_require__(61411); + +// src/submodules/sso-oidc/models/models_0.ts +var import_smithy_client4 = __nccwpck_require__(61411); + +// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts +var import_smithy_client3 = __nccwpck_require__(61411); +var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { + static { + __name(this, "SSOOIDCServiceException"); } - return input; -}; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); } - return monthIdx + 1; }; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; + +// src/submodules/sso-oidc/models/models_0.ts +var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { + static { + __name(this, "AccessDeniedException"); } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + name = "AccessDeniedException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be access_denied.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); +var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { + static { + __name(this, "AuthorizationPendingException"); } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; + name = "AuthorizationPendingException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * authorization_pending.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - return strictParseFloat32("0." + value) * 1e3; }; -var parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); +var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenRequestFilterSensitiveLog"); +var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { + static { + __name(this, "ExpiredTokenException"); + } + name = "ExpiredTokenException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be expired_token.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; }; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; +var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { + static { + __name(this, "InternalServerException"); } - if (idx === 0) { - return value; + name = "InternalServerException"; + $fault = "server"; + /** + *

Single error code. For this exception the value will be server_error.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - return value.slice(idx); -}; - -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(12048); - -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - } - }); - return str; }; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); +var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { + static { + __name(this, "InvalidClientException"); + } + name = "InvalidClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * invalid_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - return LazyJsonString(JSON.stringify(object)); }; -LazyJsonString.fromObject = LazyJsonString.from; - -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; +var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { + static { + __name(this, "InvalidGrantException"); } - return part; -} - -// src/submodules/serde/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + name = "InvalidGrantException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_grant.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; +}; +var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { + static { + __name(this, "InvalidRequestException"); } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } + name = "InvalidRequestException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * invalid_request.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); +}; +var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { + static { + __name(this, "InvalidScopeException"); } - return compoundSegments; -} - -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - default: - } - prevChar = char; + name = "InvalidScopeException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_scope.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; - } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); - } - return v.replace(/\\"/g, '"'); - }); }; - -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); - } - dot = 1; - continue; - } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); - } - } - } - toString() { - return this.string; +var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { + static { + __name(this, "SlowDownException"); } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; - } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); - if (prototypeMatch) { - return prototypeMatch; - } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { - return true; - } - return prototypeMatch; + name = "SlowDownException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be slow_down.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 9136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { + static { + __name(this, "UnauthorizedClientException"); + } + name = "UnauthorizedClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * unauthorized_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(index_exports); - -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(20843); -var import_querystring_builder = __nccwpck_require__(14959); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 }; -var FetchHttpHandler = class _FetchHttpHandler { +var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { static { - __name(this, "FetchHttpHandler"); + __name(this, "UnsupportedGrantTypeException"); } + name = "UnsupportedGrantTypeException"; + $fault = "client"; /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + *

Single error code. For this exception the value will be + * unsupported_grant_type.

+ * @public */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts }); - } - httpHandlerConfigs() { - return this.config ?? {}; + Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(72722); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; +// src/submodules/sso-oidc/protocols/Aws_restJson1.ts +var import_core2 = __nccwpck_require__(8704); +var import_core3 = __nccwpck_require__(22743); +var import_smithy_client5 = __nccwpck_require__(61411); +var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core3.requestBuilder)(input, context); + const headers = { + "content-type": "application/json" + }; + b.bp("/token"); + let body; + body = JSON.stringify( + (0, import_smithy_client5.take)(input, { + clientId: [], + clientSecret: [], + code: [], + codeVerifier: [], + deviceCode: [], + grantType: [], + redirectUri: [], + refreshToken: [], + scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") + }) + ); + b.m("POST").h(headers).b(body); + return b.build(); +}, "se_CreateTokenCommand"); +var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + const contents = (0, import_smithy_client5.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client5.take)(data, { + accessToken: import_smithy_client5.expectString, + expiresIn: import_smithy_client5.expectInt32, + idToken: import_smithy_client5.expectString, + refreshToken: import_smithy_client5.expectString, + tokenType: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + return contents; +}, "de_CreateTokenCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core2.parseJsonErrorBody)(output.body, context) + }; + const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body); + switch (errorCode) { + case "AccessDeniedException": + case "com.amazonaws.ssooidc#AccessDeniedException": + throw await de_AccessDeniedExceptionRes(parsedOutput, context); + case "AuthorizationPendingException": + case "com.amazonaws.ssooidc#AuthorizationPendingException": + throw await de_AuthorizationPendingExceptionRes(parsedOutput, context); + case "ExpiredTokenException": + case "com.amazonaws.ssooidc#ExpiredTokenException": + throw await de_ExpiredTokenExceptionRes(parsedOutput, context); + case "InternalServerException": + case "com.amazonaws.ssooidc#InternalServerException": + throw await de_InternalServerExceptionRes(parsedOutput, context); + case "InvalidClientException": + case "com.amazonaws.ssooidc#InvalidClientException": + throw await de_InvalidClientExceptionRes(parsedOutput, context); + case "InvalidGrantException": + case "com.amazonaws.ssooidc#InvalidGrantException": + throw await de_InvalidGrantExceptionRes(parsedOutput, context); + case "InvalidRequestException": + case "com.amazonaws.ssooidc#InvalidRequestException": + throw await de_InvalidRequestExceptionRes(parsedOutput, context); + case "InvalidScopeException": + case "com.amazonaws.ssooidc#InvalidScopeException": + throw await de_InvalidScopeExceptionRes(parsedOutput, context); + case "SlowDownException": + case "com.amazonaws.ssooidc#SlowDownException": + throw await de_SlowDownExceptionRes(parsedOutput, context); + case "UnauthorizedClientException": + case "com.amazonaws.ssooidc#UnauthorizedClientException": + throw await de_UnauthorizedClientExceptionRes(parsedOutput, context); + case "UnsupportedGrantTypeException": + case "com.amazonaws.ssooidc#UnsupportedGrantTypeException": + throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode + }); } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); +}, "de_CommandError"); +var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); +var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString }); -} -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 21109: -/***/ ((module) => { + Object.assign(contents, doc); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AccessDeniedExceptionRes"); +var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new AuthorizationPendingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AuthorizationPendingExceptionRes"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_ExpiredTokenExceptionRes"); +var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InternalServerExceptionRes"); +var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidClientExceptionRes"); +var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidGrantException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidGrantExceptionRes"); +var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidRequestExceptionRes"); +var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidScopeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidScopeExceptionRes"); +var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new SlowDownException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_SlowDownExceptionRes"); +var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnauthorizedClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnauthorizedClientExceptionRes"); +var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnsupportedGrantTypeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnsupportedGrantTypeExceptionRes"); +var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] +}), "deserializeMetadata"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { + static { + __name(this, "CreateTokenCommand"); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// src/submodules/sso-oidc/SSOOIDC.ts +var commands = { + CreateTokenCommand +}; +var SSOOIDC = class extends SSOOIDCClient { + static { + __name(this, "SSOOIDC"); + } +}; +(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 14272: +/***/ 16901: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointFromConfig = void 0; +exports.getRuntimeConfig = void 0; +const tslib_1 = __nccwpck_require__(61860); +const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(39955)); +const core_1 = __nccwpck_require__(8704); +const util_user_agent_node_1 = __nccwpck_require__(51656); +const config_resolver_1 = __nccwpck_require__(39316); +const hash_node_1 = __nccwpck_require__(5092); +const middleware_retry_1 = __nccwpck_require__(19618); const node_config_provider_1 = __nccwpck_require__(62021); -const getEndpointUrlConfig_1 = __nccwpck_require__(53219); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; +const node_http_handler_1 = __nccwpck_require__(82764); +const util_body_length_node_1 = __nccwpck_require__(13638); +const util_retry_1 = __nccwpck_require__(15518); +const runtimeConfig_shared_1 = __nccwpck_require__(1546); +const smithy_client_1 = __nccwpck_require__(61411); +const util_defaults_mode_node_1 = __nccwpck_require__(15435); +const smithy_client_2 = __nccwpck_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 53219: +/***/ 1546: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = __nccwpck_require__(30489); -const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; -const CONFIG_ENDPOINT_URL = "endpoint_url"; -const getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env) => { - const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); - const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - configFileSelector: (profile, config) => { - if (config && profile.services) { - const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); - const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl) - return endpointUrl; - } - } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(8704); +const core_2 = __nccwpck_require__(22743); +const smithy_client_1 = __nccwpck_require__(61411); +const url_parser_1 = __nccwpck_require__(60043); +const util_base64_1 = __nccwpck_require__(72722); +const util_utf8_1 = __nccwpck_require__(46090); +const httpAuthSchemeProvider_1 = __nccwpck_require__(8396); +const endpointResolver_1 = __nccwpck_require__(90546); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 42628: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +/***/ 63723: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/index.ts -var index_exports = {}; -__export(index_exports, { - endpointMiddleware: () => endpointMiddleware, - endpointMiddlewareOptions: () => endpointMiddlewareOptions, - getEndpointFromInstructions: () => getEndpointFromInstructions, - getEndpointPlugin: () => getEndpointPlugin, - resolveEndpointConfig: () => resolveEndpointConfig, - resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, - resolveParams: () => resolveParams, - toEndpointV1: () => toEndpointV1 -}); -module.exports = __toCommonJS(index_exports); +"use strict"; -// src/service-customizations/s3.ts -var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = __nccwpck_require__(52590); +const middleware_logger_1 = __nccwpck_require__(85242); +const middleware_recursion_detection_1 = __nccwpck_require__(81568); +const middleware_user_agent_1 = __nccwpck_require__(32959); +const config_resolver_1 = __nccwpck_require__(39316); +const core_1 = __nccwpck_require__(22743); +const middleware_content_length_1 = __nccwpck_require__(47212); +const middleware_endpoint_1 = __nccwpck_require__(42628); +const middleware_retry_1 = __nccwpck_require__(19618); +const smithy_client_1 = __nccwpck_require__(61411); +Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); +const httpAuthSchemeProvider_1 = __nccwpck_require__(27851); +const EndpointParameters_1 = __nccwpck_require__(76811); +const runtimeConfig_1 = __nccwpck_require__(36578); +const runtimeExtensions_1 = __nccwpck_require__(37742); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); } - } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { - endpointParams.ForcePathStyle = true; - } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; - } - return endpointParams; -}, "resolveParamsForS3"); -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); - } - return isValidArn; -}, "isArnBucketName"); - -// src/adaptors/createConfigValueProvider.ts -var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { - const configProvider = /* @__PURE__ */ __name(async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); + destroy() { + super.destroy(); } - return configValue; - }, "configProvider"); - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config.isCustomEndpoint === false) { - return void 0; - } - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname, port, path } = endpoint; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; - } - } - return endpoint; - }; - } - return configProvider; -}, "createConfigValueProvider"); +} +exports.STSClient = STSClient; -// src/adaptors/getEndpointFromInstructions.ts -var import_getEndpointFromConfig = __nccwpck_require__(14272); -// src/adaptors/toEndpointV1.ts -var import_url_parser = __nccwpck_require__(60043); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return (0, import_url_parser.parseUrl)(endpoint.url); - } - return endpoint; - } - return (0, import_url_parser.parseUrl)(endpoint); -}, "toEndpointV1"); +/***/ }), -// src/adaptors/getEndpointFromInstructions.ts -var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); - } else { - endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); - } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; - } - } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); - } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}, "getEndpointFromInstructions"); -var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); - break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); - break; - default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); - } - } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; -}, "resolveParams"); +/***/ 34532: +/***/ ((__unused_webpack_module, exports) => { -// src/endpointMiddleware.ts -var import_core = __nccwpck_require__(22743); -var import_util_middleware = __nccwpck_require__(99755); -var endpointMiddleware = /* @__PURE__ */ __name(({ - config, - instructions -}) => { - return (next, context) => async (args) => { - if (config.isCustomEndpoint) { - (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); - } - const endpoint = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; - } - }, - { ...config }, - context - ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign( - httpAuthOption.signingProperties || {}, - { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet - }, - authScheme.properties - ); - } - } - return next({ - ...args - }); - }; -}, "endpointMiddleware"); +"use strict"; -// src/getEndpointPlugin.ts -var import_middleware_serde = __nccwpck_require__(62654); -var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; }; -var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - endpointMiddleware({ - config, - instructions - }), - endpointMiddlewareOptions - ); - }, "applyToStack") -}), "getEndpointPlugin"); - -// src/resolveEndpointConfig.ts - -var import_getEndpointFromConfig2 = __nccwpck_require__(14272); -var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), - useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) - }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); - } - return configuredEndpointPromise; - }; - return resolvedConfig; -}, "resolveEndpointConfig"); - -// src/resolveEndpointRequiredConfig.ts -var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - throw new Error( - "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." - ); +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), }; - } - return input; -}, "resolveEndpointRequiredConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; /***/ }), -/***/ 62654: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +/***/ 27851: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/index.ts -var index_exports = {}; -__export(index_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption -}); -module.exports = __toCommonJS(index_exports); +"use strict"; -// src/deserializerMiddleware.ts -var import_protocol_http = __nccwpck_require__(20843); -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(8704); +const util_middleware_1 = __nccwpck_require__(99755); +const STSClient_1 = __nccwpck_require__(63723); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { return { - response, - output: parsed + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); } - } catch (e) { - } } - throw error; - } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); - -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); - -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true + return options; }; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); }; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: /* @__PURE__ */ __name((commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, "applyToStack") - }; -} -__name(getSerdePlugin, "getSerdePlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; /***/ }), -/***/ 62021: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 76811: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/configLoader.ts - -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(64181); -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } -} -__name(getSelectorName, "getSelectorName"); +/***/ }), -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); - } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); - } -}, "fromEnv"); +/***/ 59765: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/fromSharedConfigFiles.ts +"use strict"; -var import_shared_ini_file_loader = __nccwpck_require__(30489); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); - } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(83068); +const util_endpoints_2 = __nccwpck_require__(79674); +const ruleset_1 = __nccwpck_require__(31670); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; -// src/fromStatic.ts -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +/***/ }), -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 31670: +/***/ ((__unused_webpack_module, exports) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ruleSet = void 0; +const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; +const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "String" }, n = { [F]: true, "default": false, [G]: "Boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; +const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; +exports.ruleSet = _data; /***/ }), -/***/ 82764: +/***/ 1136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __create = Object.create; +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -77016,965 +65833,1068 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/sts/index.ts var index_exports = {}; __export(index_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector + AssumeRoleCommand: () => AssumeRoleCommand, + AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, + AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, + AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, + AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, + ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, + CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + IDPCommunicationErrorException: () => IDPCommunicationErrorException, + IDPRejectedClaimException: () => IDPRejectedClaimException, + InvalidIdentityTokenException: () => InvalidIdentityTokenException, + MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, + PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, + RegionDisabledException: () => RegionDisabledException, + STS: () => STS, + STSServiceException: () => STSServiceException, + decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + getDefaultRoleAssumer: () => getDefaultRoleAssumer2, + getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(63723), module.exports); -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(20843); -var import_querystring_builder = __nccwpck_require__(14959); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; +// src/submodules/sts/STS.ts +var import_smithy_client6 = __nccwpck_require__(61411); -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); +// src/submodules/sts/commands/AssumeRoleCommand.ts +var import_middleware_endpoint = __nccwpck_require__(42628); +var import_middleware_serde = __nccwpck_require__(62654); +var import_smithy_client4 = __nccwpck_require__(61411); +var import_EndpointParameters = __nccwpck_require__(76811); -// src/timing.ts -var timing = { - setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), - clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") -}; +// src/submodules/sts/models/models_0.ts +var import_smithy_client2 = __nccwpck_require__(61411); -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; +// src/submodules/sts/models/STSServiceException.ts +var import_smithy_client = __nccwpck_require__(61411); +var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "STSServiceException"); } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); +}; -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; +// src/submodules/sts/models/models_0.ts +var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } +}), "CredentialsFilterSensitiveLog"); +var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { + static { + __name(this, "ExpiredTokenException"); } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; + name = "ExpiredTokenException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; +}; +var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { + static { + __name(this, "MalformedPolicyDocumentException"); + } + name = "MalformedPolicyDocumentException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); +}; +var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { + static { + __name(this, "PackedPolicyTooLargeException"); } - if (sendBody) { - writeBody(httpRequest, request.body); + name = "PackedPolicyTooLargeException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; +}; +var RegionDisabledException = class _RegionDisabledException extends STSServiceException { + static { + __name(this, "RegionDisabledException"); } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; + name = "RegionDisabledException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _RegionDisabledException.prototype); } - httpRequest.end(); -} -__name(writeBody, "writeBody"); - -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } +}; +var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + static { + __name(this, "IDPRejectedClaimException"); + } + name = "IDPRejectedClaimException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); } +}; +var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { static { - __name(this, "NodeHttpHandler"); + __name(this, "InvalidIdentityTokenException"); } + name = "InvalidIdentityTokenException"; + $fault = "client"; /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * @internal */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + } +}; +var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } +}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); +var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); +var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { + static { + __name(this, "IDPCommunicationErrorException"); } + name = "IDPCommunicationErrorException"; + $fault = "client"; /** * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; +}; + +// src/submodules/sts/protocols/Aws_query.ts +var import_core = __nccwpck_require__(8704); +var import_protocol_http = __nccwpck_require__(20843); +var import_smithy_client3 = __nccwpck_require__(61411); +var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleRequest(input, context), + [_A]: _AR, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleCommand"); +var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithWebIdentityRequest(input, context), + [_A]: _ARWWI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleWithWebIdentityCommand"); +var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleCommand"); +var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleWithWebIdentityCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core.parseXmlErrorBody)(output.body, context) + }; + const errorCode = loadQueryErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "ExpiredTokenException": + case "com.amazonaws.sts#ExpiredTokenException": + throw await de_ExpiredTokenExceptionRes(parsedOutput, context); + case "MalformedPolicyDocument": + case "com.amazonaws.sts#MalformedPolicyDocumentException": + throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); + case "PackedPolicyTooLarge": + case "com.amazonaws.sts#PackedPolicyTooLargeException": + throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); + case "RegionDisabledException": + case "com.amazonaws.sts#RegionDisabledException": + throw await de_RegionDisabledExceptionRes(parsedOutput, context); + case "IDPCommunicationError": + case "com.amazonaws.sts#IDPCommunicationErrorException": + throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); + case "IDPRejectedClaim": + case "com.amazonaws.sts#IDPRejectedClaimException": + throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context); + case "InvalidIdentityToken": + case "com.amazonaws.sts#InvalidIdentityTokenException": + throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody: parsedBody.Error, + errorCode }); + } +}, "de_CommandError"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_ExpiredTokenException(body.Error, context); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_ExpiredTokenExceptionRes"); +var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPCommunicationErrorException(body.Error, context); + const exception = new IDPCommunicationErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPCommunicationErrorExceptionRes"); +var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPRejectedClaimException(body.Error, context); + const exception = new IDPRejectedClaimException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPRejectedClaimExceptionRes"); +var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidIdentityTokenException(body.Error, context); + const exception = new InvalidIdentityTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_InvalidIdentityTokenExceptionRes"); +var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_MalformedPolicyDocumentException(body.Error, context); + const exception = new MalformedPolicyDocumentException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_MalformedPolicyDocumentExceptionRes"); +var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_PackedPolicyTooLargeException(body.Error, context); + const exception = new PackedPolicyTooLargeException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_PackedPolicyTooLargeExceptionRes"); +var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_RegionDisabledException(body.Error, context); + const exception = new RegionDisabledException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_RegionDisabledExceptionRes"); +var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; + } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T], context); + if (input[_T]?.length === 0) { + entries.Tags = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; }); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + if (input[_TTK] != null) { + const memberEntries = se_tagKeyListType(input[_TTK], context); + if (input[_TTK]?.length === 0) { + entries.TransitiveTagKeys = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TransitiveTagKeys.${key}`; + entries[loc] = value; }); } - httpHandlerConfigs() { - return this.config ?? {}; + if (input[_EI] != null) { + entries[_EI] = input[_EI]; } -}; - -// src/node-http2-handler.ts - - -var import_http22 = __nccwpck_require__(85675); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); - -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; + if (input[_SN] != null) { + entries[_SN] = input[_SN]; } - static { - __name(this, "NodeHttp2ConnectionPool"); + if (input[_TC] != null) { + entries[_TC] = input[_TC]; } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); + if (input[_SI] != null) { + entries[_SI] = input[_SI]; + } + if (input[_PC] != null) { + const memberEntries = se_ProvidedContextsListType(input[_PC], context); + if (input[_PC]?.length === 0) { + entries.ProvidedContexts = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `ProvidedContexts.${key}`; + entries[loc] = value; + }); } - offerLast(session) { - this.sessions.push(session); + return entries; +}, "se_AssumeRoleRequest"); +var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - contains(session) { - return this.sessions.includes(session); + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); + if (input[_WIT] != null) { + entries[_WIT] = input[_WIT]; } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); + if (input[_PI] != null) { + entries[_PI] = input[_PI]; } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } -}; - -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } + if (input[_P] != null) { + entries[_P] = input[_P]; } - static { - __name(this, "NodeHttp2ConnectionManager"); + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); - } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + return entries; +}, "se_AssumeRoleWithWebIdentityRequest"); +var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; + const memberEntries = se_PolicyDescriptorType(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; + return entries; +}, "se_policyDescriptorListType"); +var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_a] != null) { + entries[_a] = input[_a]; + } + return entries; +}, "se_PolicyDescriptorType"); +var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_PAr] != null) { + entries[_PAr] = input[_PAr]; + } + if (input[_CA] != null) { + entries[_CA] = input[_CA]; + } + return entries; +}, "se_ProvidedContext"); +var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); + const memberEntries = se_ProvidedContext(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); + return entries; +}, "se_ProvidedContextsListType"); +var se_Tag = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_K] != null) { + entries[_K] = input[_K]; } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); + if (input[_Va] != null) { + entries[_Va] = input[_Va]; + } + return entries; +}, "se_Tag"); +var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } + entries[`member.${counter}`] = entry; + counter++; } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + return entries; +}, "se_tagKeyListType"); +var se_tagListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - this.config.maxConcurrency = maxConcurrentStreams; + const memberEntries = se_Tag(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; + return entries; +}, "se_tagListType"); +var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_ARI] != null) { + contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); } - getUrlString(request) { - return request.destination.toString(); + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); } -}; - -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); + return contents; +}, "de_AssumedRoleUser"); +var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - static { - __name(this, "NodeHttp2Handler"); + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); } - destroy() { - this.connectionManager.destroy(); + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); + return contents; +}, "de_AssumeRoleResponse"); +var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); + if (output[_SFWIT] != null) { + contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + } + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + } + if (output[_Pr] != null) { + contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); + } + if (output[_Au] != null) { + contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); + } + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + } + return contents; +}, "de_AssumeRoleWithWebIdentityResponse"); +var de_Credentials = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_AKI] != null) { + contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); + } + if (output[_SAK] != null) { + contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); + } + if (output[_ST] != null) { + contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); + } + if (output[_E] != null) { + contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); + } + return contents; +}, "de_Credentials"); +var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_ExpiredTokenException"); +var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPCommunicationErrorException"); +var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPRejectedClaimException"); +var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_InvalidIdentityTokenException"); +var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_MalformedPolicyDocumentException"); +var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - httpHandlerConfigs() { - return this.config ?? {}; + return contents; +}, "de_PackedPolicyTooLargeException"); +var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } + return contents; +}, "de_RegionDisabledException"); +var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] +}), "deserializeMetadata"); +var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); +var buildHttpRpcRequest = /* @__PURE__ */ __name(async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers + }; + if (resolvedHostname !== void 0) { + contents.hostname = resolvedHostname; + } + if (body !== void 0) { + contents.body = body; } + return new import_protocol_http.HttpRequest(contents); +}, "buildHttpRpcRequest"); +var SHARED_HEADERS = { + "content-type": "application/x-www-form-urlencoded" }; - -// src/stream-collector/collector.ts - -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; +var _ = "2011-06-15"; +var _A = "Action"; +var _AKI = "AccessKeyId"; +var _AR = "AssumeRole"; +var _ARI = "AssumedRoleId"; +var _ARU = "AssumedRoleUser"; +var _ARWWI = "AssumeRoleWithWebIdentity"; +var _Ar = "Arn"; +var _Au = "Audience"; +var _C = "Credentials"; +var _CA = "ContextAssertion"; +var _DS = "DurationSeconds"; +var _E = "Expiration"; +var _EI = "ExternalId"; +var _K = "Key"; +var _P = "Policy"; +var _PA = "PolicyArns"; +var _PAr = "ProviderArn"; +var _PC = "ProvidedContexts"; +var _PI = "ProviderId"; +var _PPS = "PackedPolicySize"; +var _Pr = "Provider"; +var _RA = "RoleArn"; +var _RSN = "RoleSessionName"; +var _SAK = "SecretAccessKey"; +var _SFWIT = "SubjectFromWebIdentityToken"; +var _SI = "SourceIdentity"; +var _SN = "SerialNumber"; +var _ST = "SessionToken"; +var _T = "Tags"; +var _TC = "TokenCode"; +var _TTK = "TransitiveTagKeys"; +var _V = "Version"; +var _Va = "Value"; +var _WIT = "WebIdentityToken"; +var _a = "arn"; +var _m = "message"; +var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); +var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { + if (data.Error?.Code !== void 0) { + return data.Error.Code; + } + if (output.statusCode == 404) { + return "NotFound"; } +}, "loadQueryErrorCode"); + +// src/submodules/sts/commands/AssumeRoleCommand.ts +var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { static { - __name(this, "Collector"); + __name(this, "AssumeRoleCommand"); } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); +}; + +// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(42628); +var import_middleware_serde2 = __nccwpck_require__(62654); +var import_smithy_client5 = __nccwpck_require__(61411); +var import_EndpointParameters2 = __nccwpck_require__(76811); +var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { + static { + __name(this, "AssumeRoleWithWebIdentityCommand"); } }; -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/submodules/sts/STS.ts +var import_STSClient = __nccwpck_require__(63723); +var commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand +}; +var STS = class extends import_STSClient.STSClient { + static { + __name(this, "STS"); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; +}; +(0, import_smithy_client6.createAggregatedClient)(commands, STS); + +// src/submodules/sts/index.ts +var import_EndpointParameters3 = __nccwpck_require__(76811); + +// src/submodules/sts/defaultStsRoleAssumers.ts +var import_client = __nccwpck_require__(5152); +var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); -// Annotate the CommonJS export names for ESM import in node: + return void 0; +}, "getAccountIdFromAssumedRoleUser"); +var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + credentialProviderLogger?.debug?.( + "@aws-sdk/client-sts::resolveRegion", + "accepting first of:", + `${region} (provider)`, + `${parentRegion} (parent client)`, + `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` + ); + return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; +}, "resolveRegion"); +var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + // A hack to make sts client uses the credential in current closure. + credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); + } + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}, "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); + } + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + if (accountId) { + (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}, "getDefaultRoleAssumerWithWebIdentity"); +var isH2 = /* @__PURE__ */ __name((requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}, "isH2"); +// src/submodules/sts/defaultRoleAssumers.ts +var import_STSClient2 = __nccwpck_require__(63723); +var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { + if (!customizations) return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + static { + __name(this, "CustomizableSTSClient"); + } + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}, "getCustomizableStsClientCtor"); +var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); +var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer2(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), + ...input +}), "decorateDefaultCredentialProvider"); +// Annotate the CommonJS export names for ESM import in node: 0 && (0); - /***/ }), -/***/ 64181: -/***/ ((module) => { +/***/ 36578: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const tslib_1 = __nccwpck_require__(61860); +const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(39955)); +const core_1 = __nccwpck_require__(8704); +const util_user_agent_node_1 = __nccwpck_require__(51656); +const config_resolver_1 = __nccwpck_require__(39316); +const core_2 = __nccwpck_require__(22743); +const hash_node_1 = __nccwpck_require__(5092); +const middleware_retry_1 = __nccwpck_require__(19618); +const node_config_provider_1 = __nccwpck_require__(62021); +const node_http_handler_1 = __nccwpck_require__(82764); +const util_body_length_node_1 = __nccwpck_require__(13638); +const util_retry_1 = __nccwpck_require__(15518); +const runtimeConfig_shared_1 = __nccwpck_require__(24443); +const smithy_client_1 = __nccwpck_require__(61411); +const util_defaults_mode_node_1 = __nccwpck_require__(15435); +const smithy_client_2 = __nccwpck_require__(61411); +const getRuntimeConfig = (config) => { + (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); + (0, core_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, + }, config), + sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +exports.getRuntimeConfig = getRuntimeConfig; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; +/***/ }), -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; +/***/ 24443: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(8704); +const core_2 = __nccwpck_require__(22743); +const smithy_client_1 = __nccwpck_require__(61411); +const url_parser_1 = __nccwpck_require__(60043); +const util_base64_1 = __nccwpck_require__(72722); +const util_utf8_1 = __nccwpck_require__(46090); +const httpAuthSchemeProvider_1 = __nccwpck_require__(27851); +const endpointResolver_1 = __nccwpck_require__(59765); +const getRuntimeConfig = (config) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "STS", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; }; +exports.getRuntimeConfig = getRuntimeConfig; -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +/***/ }), -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 37742: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveRuntimeExtensions = void 0; +const region_config_resolver_1 = __nccwpck_require__(36463); +const protocol_http_1 = __nccwpck_require__(20843); +const smithy_client_1 = __nccwpck_require__(61411); +const httpAuthExtensionConfiguration_1 = __nccwpck_require__(34532); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), -/***/ 20843: +/***/ 22743: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -77999,290 +66919,410 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature }); module.exports = __toCommonJS(index_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts +// src/getSmithyContext.ts var import_types = __nccwpck_require__(65165); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(99755); + +// src/middleware-http-auth-scheme/resolveAuthOptions.ts +var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + return preferredAuthOptions; +}, "resolveAuthOptions"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + return map; +} +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + ); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); } + return next(args); +}, "httpAuthSchemeMiddleware"); + +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" }; +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(62654); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); + }, "applyToStack") +}), "getHttpAuthSchemePlugin"); -// src/httpRequest.ts +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(20843); -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); + +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" +}; +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + }, "applyToStack") +}), "getHttpSigningPlugin"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); + +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + return void 0; + }, "paginateOperation"); +} +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); + cursor = cursor[step]; } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param + return cursor; +}, "get"); + +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(14097); + +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} }; - }, {}); + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; } -__name(cloneQuery, "cloneQuery"); +__name(setFeature, "setFeature"); -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { + /** + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure + */ + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; + static { + __name(this, "DefaultIdentityProviderConfig"); } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); } }; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts -/***/ }), +var HttpApiKeyAuthSigner = class { + static { + __name(this, "HttpApiKeyAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); + } + return clonedRequest; + } +}; -/***/ 14959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +var HttpBearerAuthSigner = class { + static { + __name(this, "HttpBearerAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { + static { + __name(this, "NoAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + return httpRequest; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(index_exports); -var import_util_uri_escape = __nccwpck_require__(87377); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -78291,14 +67331,13 @@ __name(buildQueryString, "buildQueryString"); /***/ }), -/***/ 15183: -/***/ ((module) => { +/***/ 74992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -78313,128 +67352,260 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/event-streams/index.ts var index_exports = {}; __export(index_exports, { - parseQueryString: () => parseQueryString + EventStreamSerde: () => EventStreamSerde }); module.exports = __toCommonJS(index_exports); -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); + +// src/submodules/event-streams/EventStreamSerde.ts +var import_schema = __nccwpck_require__(67635); +var import_util_utf8 = __nccwpck_require__(46090); +var EventStreamSerde = class { + /** + * Properties are injected by the HttpProtocol. + */ + constructor({ + marshaller, + serializer, + deserializer, + serdeContext, + defaultContentType + }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + } + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType } + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body + }; + } + for await (const page of eventStream) { + yield page; + } } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody( + unionMember, + unionSchema, + event + ); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders + }; + return { + headers, + body + }; + }); + } + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream for the end-user. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, event[unionMember].body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject + }; + } else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, event[unionMember].body) + }; } else { - query[key] = [query[key], value]; + return { + $unknown: event + }; } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; } - } - return query; -} -__name(parseQueryString, "parseQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 23327: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error( + "@smithy::core/protocols - initial-response event encountered in event stream but no response schema given." + ); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; - - -/***/ }), - -/***/ 72412: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(23327); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; - - -/***/ }), - -/***/ 27539: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(72412); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + } + }; + } + /** + * @param unionMember - member name within the structure that contains an event stream union. + * @param unionSchema - schema of the union. + * @param event + * + * @returns the event body (bytes) and event type (string). + */ + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = unionSchema.hasMemberSchema(unionMember); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(import_schema.SCHEMA.DOCUMENT, value); + } else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + break; + } else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } else { + type = "long"; + } + } else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } else if (memberSchema.isStringSchema()) { + type = "string"; + } else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } else { + serializer.write(eventSchema, event[unionMember]); + } + } else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); + const messageSerialization = serializer.flush(); + const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders + }; + } }; -exports.getSSOTokenFromFile = getSSOTokenFromFile; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 30489: +/***/ 14097: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -78447,1606 +67618,1716 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/protocols/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + HttpProtocol: () => HttpProtocol, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(23327), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/index.ts -__reExport(index_exports, __nccwpck_require__(72412), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(27539); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(65165); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(64691); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(23327); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}; -var import_getHomeDir2 = __nccwpck_require__(23327); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(23327); +// src/submodules/protocols/HttpBindingProtocol.ts +var import_schema2 = __nccwpck_require__(67635); +var import_serde = __nccwpck_require__(65409); +var import_protocol_http2 = __nccwpck_require__(20843); +var import_util_stream2 = __nccwpck_require__(64691); -// src/parseIni.ts +// src/submodules/protocols/HttpProtocol.ts +var import_schema = __nccwpck_require__(67635); +var import_protocol_http = __nccwpck_require__(20843); +var HttpProtocol = class { + constructor(options) { + this.options = options; + } + getRequestType() { + return import_protocol_http.HttpRequest; + } + getResponseType() { + return import_protocol_http.HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + for (const [k, v] of endpoint.url.searchParams.entries()) { + if (!request.query) { + request.query = {}; + } + request.query[k] = v; + } + return request; + } else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const operationNs = import_schema.NormalizedSchema.of(operationSchema); + const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter( + ([, member]) => member.getMergedTraits().hostLabel + ); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }; + } + /** + * @param eventStream - the iterable provided by the caller. + * @param requestSchema - the schema of the event stream container (struct). + * @param [initialRequest] - only provided if the initial-request is part of the event stream (RPC). + * + * @returns a stream suitable for the HTTP body of a request. + */ + async serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }); + } + /** + * @param response - http response from which to read the event stream. + * @param unionSchema - schema of the event stream container (struct). + * @param [initialResponseContainer] - provided and written to only if the initial response is part of the event stream (RPC). + * + * @returns the asyncIterable of the event stream. + */ + async deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }); + } + /** + * Loads eventStream capability async (for chunking). + */ + async loadEventStreamCapability() { + const { EventStreamSerde } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(74992))); + return new EventStreamSerde({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType() + }); + } + /** + * @returns content-type default header value for event stream events and other documents. + */ + getDefaultContentType() { + throw new Error( + `@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.` + ); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + void schema; + void context; + void response; + void arg4; + void arg5; + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } +}; -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); +// src/submodules/protocols/HttpBindingProtocol.ts +var HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ..._input ?? {} + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new import_protocol_http2.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns + }); + } + } else { + payload = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace( + `{${memberName}+}`, + replacement.split("/").map(extendedEncodeURIComponent).join("/") + ); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; + } else { + hasNonHttpBindingMember = true; + } + } + if (hasNonHttpBindingMember && input) { + serializer.write(schema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + // We pass on the traits to the sub-schema + // because we are still in the process of serializing the map itself. + ...traits, + httpQuery: key, + httpQueryParams: void 0 + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; + } + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } else { + dataObject = arg4; + } + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { + sections = (0, import_serde.splitEvery)(value, ",", 2); + } else { + sections = (0, import_serde.splitHeader)(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( + valueSchema, + value + ); } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; } - } - } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(47307); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(47307); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); - -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; } else { - merged[key] = values; + nonHttpBindingMembers.push(memberName); } } + return nonHttpBindingMembers; } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); - -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(27539); -var import_slurpFile3 = __nccwpck_require__(47307); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 47307: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; - - -/***/ }), - -/***/ 65165: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") +// src/submodules/protocols/RpcProtocol.ts +var import_schema3 = __nccwpck_require__(67635); +var import_protocol_http3 = __nccwpck_require__(20843); +var RpcProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 60043: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseUrl: () => parseUrl -}); -module.exports = __toCommonJS(index_exports); -var import_querystring_parser = __nccwpck_require__(15183); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 95895: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(21266); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); + const _input = { + ...input + }; + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (_input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && _input[memberName]) { + serializer.write(memberSchema, _input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload = await this.serializeEventStream({ + eventStream: _input[eventStreamMember], + requestSchema: ns, + initialRequest + }); + } + } else { + serializer.write(schema, _input); + payload = serializer.flush(); + } } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); -}; -exports.fromBase64 = fromBase64; - - -/***/ }), - -/***/ 72722: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(95895), module.exports); -__reExport(index_exports, __nccwpck_require__(97234), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 97234: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(21266); -const util_utf8_1 = __nccwpck_require__(46090); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema3.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); } - else { - input = _input; + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject + }); + } else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - - -/***/ }), - -/***/ 21266: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(21109); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), -/***/ 79916: -/***/ ((module) => { +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http4 = __nccwpck_require__(20843); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); } - return to; + return resolvedPath2; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); } -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); } + return new import_protocol_http4.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 99755: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; + } + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; + } + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(65165); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var import_schema5 = __nccwpck_require__(67635); +var import_serde2 = __nccwpck_require__(65409); +var import_util_base64 = __nccwpck_require__(72722); +var import_util_utf8 = __nccwpck_require__(46090); - -/***/ }), - -/***/ 79241: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; +// src/submodules/protocols/serde/determineTimestampFormat.ts +var import_schema4 = __nccwpck_require__(67635); +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { + return ns.getSchema(); } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; } -exports.ByteArrayCollector = ByteArrayCollector; - - -/***/ }), - -/***/ 34778: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 72116: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(72722); -const stream_1 = __nccwpck_require__(2203); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var FromStringShapeDeserializer = class { + constructor(settings) { + this.settings = settings; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + read(_schema, data) { + const ns = import_schema5.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); + case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(data); + case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); } - catch (e) { - return callback(e); + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); } - this.push(null); - return callback(); - } -} -exports.ChecksumStream = ChecksumStream; - - -/***/ }), - -/***/ 49158: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(72722); -const stream_type_check_1 = __nccwpck_require__(37785); -const ChecksumStream_browser_1 = __nccwpck_require__(34778); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + return intermediateValue; + } } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + switch (true) { + case ns.isNumericSchema(): + return Number(data); + case ns.isBigIntegerSchema(): + return BigInt(data); + case ns.isBigDecimalSchema(): + return new import_serde2.NumericValue(data, "bigDecimal"); + case ns.isBooleanSchema(): + return String(data).toLowerCase() === "true"; } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + } }; -exports.createChecksumStream = createChecksumStream; - - -/***/ }), - -/***/ 32384: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(37785); -const ChecksumStream_1 = __nccwpck_require__(72116); -const createChecksumStream_browser_1 = __nccwpck_require__(49158); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} - - -/***/ }), - -/***/ 40260: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(57075); -const ByteArrayCollector_1 = __nccwpck_require__(79241); -const createBufferedReadableStream_1 = __nccwpck_require__(34335); -const stream_type_check_1 = __nccwpck_require__(37785); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; +// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts +var import_schema6 = __nccwpck_require__(67635); +var import_util_utf82 = __nccwpck_require__(46090); +var HttpInterceptingShapeDeserializer = class { + constructor(codecDeserializer, codecSettings) { + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema, data) { + const ns = import_schema6.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; + if (typeof data === "string") { + return toBytes(data); } - if (mode === -1) { - downstream.push(chunk); - return; + return data; + } else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); + return data; + } + } + return this.codecDeserializer.read(ns, data); + } +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var import_schema8 = __nccwpck_require__(67635); + +// src/submodules/protocols/serde/ToStringShapeSerializer.ts +var import_schema7 = __nccwpck_require__(67635); +var import_serde3 = __nccwpck_require__(65409); +var import_util_base642 = __nccwpck_require__(72722); +var ToStringShapeSerializer = class { + constructor(settings) { + this.settings = settings; + this.stringBuffer = ""; + this.serdeContext = void 0; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + write(schema, value) { + const ns = import_schema7.NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error( + `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName( + true + )}` + ); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: + this.stringBuffer = (0, import_serde3.dateToUtcString)(value); + break; + case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; } - downstream.push(null); - }); - return downstream; -} - - -/***/ }), - -/***/ 34335: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(79241); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); + if (buffer !== "") { + buffer += ", "; } - controller.close(); + buffer += serialized; + } + this.stringBuffer = buffer; + return; } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); } - if (chunk instanceof Uint8Array) { - return 1; + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var HttpInterceptingShapeSerializer = class { + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = import_schema8.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; } - if (typeof chunk === "string") { - return 0; + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== void 0) { + const buffer = this.buffer; + this.buffer = void 0; + return buffer; } - return -1; -} + return this.codecSerializer.flush(); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 22505: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 67635: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); +// src/submodules/schema/index.ts +var index_exports = {}; +__export(index_exports, { + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + list: () => list, + map: () => map, + op: () => op, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + struct: () => struct +}); +module.exports = __toCommonJS(index_exports); + +// src/submodules/schema/deref.ts +var deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts +var import_protocol_http = __nccwpck_require__(20843); +var import_util_middleware = __nccwpck_require__(99755); +var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + try { + const parsed = await config.protocol.deserializeResponse( + operationSchema, + { + ...config, + ...context + }, + response + ); + return { + response, + output: parsed + }; + } catch (error2) { + Object.defineProperty(error2, "$response", { + value: response }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); + if (!("$metadata" in error2)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error2.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; + } + if (typeof error2.$responseBodyText !== "undefined") { + if (error2.$response) { + error2.$response.body = error2.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error2.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { + } + } + throw error2; + } +}; +var findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; }; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; - - -/***/ }), -/***/ 45139: -/***/ ((__unused_webpack_module, exports) => { +// src/submodules/schema/middleware/schemaSerializationMiddleware.ts +var import_util_middleware2 = __nccwpck_require__(99755); +var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint + }); + return next({ + ...args, + request + }); +}; -"use strict"; +// src/submodules/schema/middleware/getSchemaSerdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + } + }; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; +// src/submodules/schema/TypeRegistry.ts +var TypeRegistry = class _TypeRegistry { + constructor(namespace, schemas = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; + } + static { + this.registries = /* @__PURE__ */ new Map(); + } + /** + * @param namespace - specifier. + * @returns the schema for that namespace, creating it if necessary. + */ + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); + } + /** + * Adds the given schema to a type registry with the same namespace. + * + * @param shapeId - to be registered. + * @param schema - to be registered. + */ + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = _TypeRegistry.for(this.getNamespace(shapeId)); + registry.schemas.set(qualifiedName, schema); + } + /** + * @param shapeId - query. + * @returns the schema. + */ + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; + return this.schemas.get(id); + } + /** + * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, + * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which + * is unique per service/model. + * + * This is generated under a unique prefix that is combined with the service namespace, and this + * method is used to retrieve it. + * + * The base exception synthetic schema is used when an error is returned by a service, but we cannot + * determine what existing schema to use to deserialize it. + * + * @returns the synthetic base exception of the service namespace associated with this registry instance. + */ + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } } - return collected; -} - - -/***/ }), - -/***/ 86901: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2203); -const headStream_browser_1 = __nccwpck_require__(45139); -const stream_type_check_1 = __nccwpck_require__(37785); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); + return void 0; + } + /** + * @param predicate - criterion. + * @returns a schema in this registry matching the predicate. + */ + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + /** + * Unloads the current TypeRegistry. + */ + destroy() { + _TypeRegistry.registries.delete(this.namespace); + this.schemas.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; + } }; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; - } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } -} +// src/submodules/schema/schemas/Schema.ts +var Schema = class { + static assign(instance, values) { + const schema = Object.assign(instance, values); + TypeRegistry.for(schema.namespace).register(schema.name, schema); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +}; -/***/ }), +// src/submodules/schema/schemas/ListSchema.ts +var ListSchema = class _ListSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _ListSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/lis"); + } +}; +var list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema +}); -/***/ 64691: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/submodules/schema/schemas/MapSchema.ts +var MapSchema = class _MapSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _MapSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/map"); + } +}; +var map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema +}); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +// src/submodules/schema/schemas/OperationSchema.ts +var OperationSchema = class _OperationSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _OperationSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/ope"); + } }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output +}); + +// src/submodules/schema/schemas/StructureSchema.ts +var StructureSchema = class _StructureSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _StructureSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/str"); } - return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList +}); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +// src/submodules/schema/schemas/ErrorSchema.ts +var ErrorSchema = class _ErrorSchema extends StructureSchema { + constructor() { + super(...arguments); + this.symbol = _ErrorSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/err"); + } +}; +var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor }); -module.exports = __toCommonJS(index_exports); -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(72722); -var import_util_utf8 = __nccwpck_require__(46090); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); +// src/submodules/schema/schemas/sentinels.ts +var SCHEMA = { + BLOB: 21, + // 21 + STREAMING_BLOB: 42, + // 42 + BOOLEAN: 2, + // 2 + STRING: 0, + // 0 + NUMERIC: 1, + // 1 + BIG_INTEGER: 17, + // 17 + BIG_DECIMAL: 19, + // 19 + DOCUMENT: 15, + // 15 + TIMESTAMP_DEFAULT: 4, + // 4 + TIMESTAMP_DATE_TIME: 5, + // 5 + TIMESTAMP_HTTP_DATE: 6, + // 6 + TIMESTAMP_EPOCH_SECONDS: 7, + // 7 + LIST_MODIFIER: 64, + // 64 + MAP_MODIFIER: 128 + // 128 +}; + +// src/submodules/schema/schemas/SimpleSchema.ts +var SimpleSchema = class _SimpleSchema extends Schema { + constructor() { + super(...arguments); + this.symbol = _SimpleSchema.symbol; } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); + static { + this.symbol = Symbol.for("@smithy/sim"); } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); +}; +var sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef +}); -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { +// src/submodules/schema/schemas/NormalizedSchema.ts +var NormalizedSchema = class _NormalizedSchema { + /** + * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. + * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. + */ + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + this.symbol = _NormalizedSchema.symbol; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema instanceof _NormalizedSchema) { + Object.assign(this, schema); + this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } static { - __name(this, "Uint8ArrayBlobAdapter"); + this.symbol = Symbol.for("@smithy/nor"); + } + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); + } + /** + * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. + */ + static of(ref) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + if (Array.isArray(ref)) { + const [ns, traits] = ref; + if (ns instanceof _NormalizedSchema) { + Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + return new _NormalizedSchema(ref); + } + /** + * @param indicator - numeric indicator for preset trait combination. + * @returns equivalent trait object. + */ + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i++ & 1) === 1) { + traits[trait] = 1; + } + } + return traits; + } + /** + * @returns the underlying non-normalized schema. + */ + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + Object.assign(this, { schema: this.schema.getSchema() }); + return this.schema; + } + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); + } + return deref(this.schema); + } + /** + * @param withNamespace - qualifies the name. + * @returns e.g. `MyShape` or `com.namespace#MyShape`. + */ + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; + } + } + return this.name || void 0; + } + /** + * @returns the member name if the schema is a member schema. + * @throws Error when the schema isn't a member schema. + */ + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + } + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + /** + * boolean methods on this class help control flow in shape serialization and deserialization. + */ + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + } + return inner instanceof ListSchema; + } + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + } + return inner instanceof MapSchema; + } + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; + } + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isTimestampSchema() { + const schema = this.getSchema(); + return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; + } + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; + } + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; + } + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; + } + return this.getSchema() === SCHEMA.STREAMING_BLOB; + } + /** + * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. + * @returns whether the schema has the idempotencyToken trait. + */ + isIdempotencyToken() { + if (typeof this.traits === "number") { + return (this.traits & 4) === 4; + } else if (typeof this.traits === "object") { + return !!this.traits.idempotencyToken; + } + return false; + } + /** + * @returns own traits merged with member traits, where member traits of the same trait key take priority. + * This method is cached. + */ + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }); } /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + * @returns only the member traits. If the schema is not a member, this returns empty. */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); } /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. + * @returns only the traits inherent to the shape or member target shape if this schema is a member. + * If there are any member traits they are excluded. */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); } /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. + * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map or Document. */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); + getKeySchema() { + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); + } + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + if (typeof schema === "number") { + return this.memberFrom([63 & schema, 0], "key"); + } + return this.memberFrom([schema.keySchema, 0], "key"); } -}; - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(72116), module.exports); -__reExport(index_exports, __nccwpck_require__(32384), module.exports); -__reExport(index_exports, __nccwpck_require__(40260), module.exports); -__reExport(index_exports, __nccwpck_require__(22505), module.exports); -__reExport(index_exports, __nccwpck_require__(86901), module.exports); -__reExport(index_exports, __nccwpck_require__(76992), module.exports); -__reExport(index_exports, __nccwpck_require__(73423), module.exports); -__reExport(index_exports, __nccwpck_require__(37785), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 65958: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(9136); -const util_base64_1 = __nccwpck_require__(72722); -const util_hex_encoding_1 = __nccwpck_require__(79916); -const util_utf8_1 = __nccwpck_require__(46090); -const stream_type_check_1 = __nccwpck_require__(37785); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + /** + * @returns the schema of the map's value or list's member. + * Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map, List, nor Document. + */ + getValueSchema() { + const schema = this.getSchema(); + if (typeof schema === "number") { + if (this.isMapSchema()) { + return this.memberFrom([63 & schema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([63 & schema, 0], "member"); + } } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 76992: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(82764); -const util_buffer_from_1 = __nccwpck_require__(21266); -const stream_1 = __nccwpck_require__(2203); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(65958); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + if (schema && typeof schema === "object") { + if (this.isStructSchema()) { + throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + } + const collection = schema; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return this.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([collection.valueSchema, 0], "member"); } + } } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; - - -/***/ }), - -/***/ 16441: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); } - const readableStream = stream; - return readableStream.tee(); -} - - -/***/ }), - -/***/ 73423: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2203); -const splitStream_browser_1 = __nccwpck_require__(16441); -const stream_type_check_1 = __nccwpck_require__(37785); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + /** + * @param member - to query. + * @returns whether there is a memberSchema with the given member name. False if not a structure (or union). + */ + hasMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + return struct2.memberNames.includes(member); } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} - - -/***/ }), - -/***/ 37785: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; - - -/***/ }), - -/***/ 87377: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return false; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 46090: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + /** + * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` + * and will have the member name given. + * @param member - which member to retrieve and wrap. + * + * @throws Error if member does not exist or the schema is neither a document nor structure. + * Note that errors are assumed to be structures and unions are considered structures for these purposes. + */ + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + if (!struct2.memberNames.includes(member)) { + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); + } + const i = struct2.memberNames.indexOf(member); + const memberSchema = struct2.memberList[i]; + return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(index_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(21266); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); + /** + * This can be used for checking the members as a hashmap. + * Prefer the structIterator method for iteration. + * + * This does NOT return list and map members, it is only for structures. + * + * @deprecated use (checked) structIterator instead. + * + * @returns a map of member names to member schemas (normalized). + */ + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } catch (ignored) { + } + return buffer; } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + /** + * @returns member name of event stream or empty string indicating none exists or this + * isn't a structure schema. + */ + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; + /** + * Allows iteration over members of a structure schema. + * Each yield is a pair of the member name and member schema. + * + * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). + */ + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct2 = this.getSchema(); + for (let i = 0; i < struct2.memberNames.length; ++i) { + yield [struct2.memberNames[i], this.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; + } } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + /** + * Creates a normalized member schema from the given schema and member name. + */ + memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); + } + return new _NormalizedSchema(memberSchema, memberName); } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); + /** + * @returns a last-resort human-readable name for the schema if it has no other identifiers. + */ + getSchemaName() { + const schema = this.getSchema(); + if (typeof schema === "number") { + const _schema = 63 & schema; + const container = 192 & schema; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; + } + } + return "Unknown"; + } +}; // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 36463: -/***/ ((module) => { - -"use strict"; +/***/ 65409: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -80061,97 +69342,668 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/serde/index.ts var index_exports = {}; __export(index_exports, { - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, - resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, - resolveRegionConfig: () => resolveRegionConfig + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger, + nv: () => nv, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort }); module.exports = __toCommonJS(index_exports); -// src/extensions/index.ts -var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; +// src/submodules/serde/copyDocumentWithTransform.ts +var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; + +// src/submodules/serde/parse-utils.ts +var parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}; +var expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +var expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}; +var expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +var expectInt = expectLong; +var expectInt32 = (value) => expectSizedInt(value, 32); +var expectShort = (value) => expectSizedInt(value, 16); +var expectByte = (value) => expectSizedInt(value, 8); +var expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +var castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +var expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}; +var expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +var expectString = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +var expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +var strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +var limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +var parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +var strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +var strictParseInt = strictParseLong; +var strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +var strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +var strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +var stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}; +var logger = { + warn: console.warn +}; + +// src/submodules/serde/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) + ); + } + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +var parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); +}; +var buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}; +var parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); + } + return input; +}; +var parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +var isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +var parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +var parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; +}; +var parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; +}; +var stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; + +// src/submodules/serde/generateIdempotencyToken.ts +var import_uuid = __nccwpck_require__(12048); + +// src/submodules/serde/lazy-json.ts +var LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); }, - region() { - return runtimeConfig.region; + toString() { + return String(val); + }, + toJSON() { + return String(val); } - }; -}, "getAwsRegionExtensionConfiguration"); -var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; -}, "resolveAwsRegionExtensionConfiguration"); - -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") + }); + return str; }; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); }; +LazyJsonString.fromObject = LazyJsonString.from; -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); +// src/submodules/serde/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); +// src/submodules/serde/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); +// src/submodules/serde/split-header.ts +var splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + default: + } + prevChar = char; } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; + } + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +// src/submodules/serde/value/NumericValue.ts +var NumericValue = class _NumericValue { + constructor(string, type) { + this.string = string; + this.type = type; + let dot = 0; + for (let i = 0; i < string.length; ++i) { + const char = string.charCodeAt(i); + if (i === 0 && char === 45) { + continue; } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; + if (char === 46) { + if (dot) { + throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); + } + dot = 1; + continue; } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); + if (char < 48 || char > 57) { + throw new Error( + `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` + ); + } + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object); + if (prototypeMatch) { + return prototypeMatch; + } + if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name?.endsWith("NumericValue")) { + return true; + } + return prototypeMatch; + } +}; +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 75433: +/***/ 9136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -80166,214 +70018,245 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - fromEnvSigningName: () => fromEnvSigningName, - fromSso: () => fromSso, - fromStatic: () => fromStatic, - nodeProvider: () => nodeProvider + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/fromEnvSigningName.ts -var import_client = __nccwpck_require__(5152); -var import_httpAuthSchemes = __nccwpck_require__(97523); -var import_property_provider = __nccwpck_require__(51515); -var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); - if (!(bearerTokenKey in process.env)) { - throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - const token = { token: process.env[bearerTokenKey] }; - (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; -}, "fromEnvSigningName"); - -// src/fromSso.ts - - - -// src/constants.ts -var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; -var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - -// src/getSsoOidcClient.ts -var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(89443))); - const ssoOidcClient = new SSOOIDCClient( - Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger - }) - ); - return ssoOidcClient; -}, "getSsoOidcClient"); - -// src/getNewSsoOidcToken.ts -var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(89443))); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send( - new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - }) - ); -}, "getNewSsoOidcToken"); - -// src/validateTokenExpiry.ts - -var validateTokenExpiry = /* @__PURE__ */ __name((token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } -}, "validateTokenExpiry"); - -// src/validateTokenKey.ts - -var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new import_property_provider.TokenProviderError( - `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, - false - ); - } -}, "validateTokenKey"); +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(20843); +var import_querystring_builder = __nccwpck_require__(14959); -// src/writeSSOTokenToFile.ts -var import_shared_ini_file_loader = __nccwpck_require__(10751); -var import_fs = __nccwpck_require__(79896); -var { writeFile } = import_fs.promises; -var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { - const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}, "writeSSOTokenToFile"); +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); -// src/fromSso.ts -var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); -var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); } - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile }); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); +} +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { + static { + __name(this, "FetchHttpHandler"); } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' could not be found in shared credentials file.`, - false - ); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); } - for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { - if (!ssoSession[ssoSessionRequiredKey]) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, - false + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") ); } } - const ssoStartUrl = ssoSession["sso_start_url"]; - const ssoRegion = ssoSession["sso_region"]; - let ssoToken; - try { - ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); - } catch (e) { - throw new import_property_provider.TokenProviderError( - `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, - false - ); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; + destroy() { } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken - }); - } catch (error) { + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials }; - } catch (error) { - validateTokenExpiry(existingToken); - return existingToken; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); } -}, "fromSso"); - -// src/fromStatic.ts - -var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + httpHandlerConfigs() { + return this.config ?? {}; } - return token; -}, "fromStatic"); - -// src/nodeProvider.ts +}; -var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)(fromSso(init), async () => { - throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); - }), - (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, - (token) => token.expiration !== void 0 -), "nodeProvider"); +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(72722); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -80382,7 +70265,7 @@ var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_pro /***/ }), -/***/ 51515: +/***/ 21109: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -80407,230 +70290,373 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize + isArrayBuffer: () => isArrayBuffer }); module.exports = __toCommonJS(index_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; +0 && (0); -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +/***/ }), -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 14272: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getEndpointFromConfig = void 0; +const node_config_provider_1 = __nccwpck_require__(62021); +const getEndpointUrlConfig_1 = __nccwpck_require__(53219); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; /***/ }), -/***/ 11593: +/***/ 53219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; +exports.getEndpointUrlConfig = void 0; +const shared_ini_file_loader_1 = __nccwpck_require__(30489); +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (config && profile.services) { + const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); +exports.getEndpointUrlConfig = getEndpointUrlConfig; + + +/***/ }), + +/***/ 42628: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; -exports.getHomeDir = getHomeDir; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + endpointMiddleware: () => endpointMiddleware, + endpointMiddlewareOptions: () => endpointMiddlewareOptions, + getEndpointFromInstructions: () => getEndpointFromInstructions, + getEndpointPlugin: () => getEndpointPlugin, + resolveEndpointConfig: () => resolveEndpointConfig, + resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, + resolveParams: () => resolveParams, + toEndpointV1: () => toEndpointV1 +}); +module.exports = __toCommonJS(index_exports); -/***/ }), +// src/service-customizations/s3.ts +var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}, "resolveParamsForS3"); +var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +var DOTS_PATTERN = /\.\./; +var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); +var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}, "isArnBucketName"); -/***/ 77366: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/adaptors/createConfigValueProvider.ts +var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { + const configProvider = /* @__PURE__ */ __name(async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }, "configProvider"); + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return void 0; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}, "createConfigValueProvider"); -"use strict"; +// src/adaptors/getEndpointFromInstructions.ts +var import_getEndpointFromConfig = __nccwpck_require__(14272); + +// src/adaptors/toEndpointV1.ts +var import_url_parser = __nccwpck_require__(60043); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return (0, import_url_parser.parseUrl)(endpoint.url); + } + return endpoint; + } + return (0, import_url_parser.parseUrl)(endpoint); +}, "toEndpointV1"); + +// src/adaptors/getEndpointFromInstructions.ts +var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; +}, "getEndpointFromInstructions"); +var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}, "resolveParams"); + +// src/endpointMiddleware.ts +var import_core = __nccwpck_require__(22743); +var import_util_middleware = __nccwpck_require__(99755); +var endpointMiddleware = /* @__PURE__ */ __name(({ + config, + instructions +}) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions( + args.input, + { + getEndpointParameterInstructions() { + return instructions; + } + }, + { ...config }, + context + ); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign( + httpAuthOption.signingProperties || {}, + { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet + }, + authScheme.properties + ); + } + } + return next({ + ...args + }); + }; +}, "endpointMiddleware"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(11593); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +// src/getEndpointPlugin.ts +var import_middleware_serde = __nccwpck_require__(62654); +var endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + endpointMiddleware({ + config, + instructions + }), + endpointMiddlewareOptions + ); + }, "applyToStack") +}), "getEndpointPlugin"); +// src/resolveEndpointConfig.ts -/***/ }), +var import_getEndpointFromConfig2 = __nccwpck_require__(14272); +var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), + useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; +}, "resolveEndpointConfig"); -/***/ 93897: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/resolveEndpointRequiredConfig.ts +var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + throw new Error( + "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." + ); + }; + } + return input; +}, "resolveEndpointRequiredConfig"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(77366); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 10751: +/***/ 62654: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -80650,201 +70676,108 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(11593), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(77366), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(93897); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(54387); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(11593); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(11593); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(11593); - -// src/parseIni.ts -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); +// src/deserializerMiddleware.ts +var import_protocol_http = __nccwpck_require__(20843); +var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); } - } else { - currentSection = sectionName; } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; } + } catch (e) { } } + throw error; } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(69545); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(69545); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +}, "deserializerMiddleware"); +var findHeader = /* @__PURE__ */ __name((pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}, "findHeader"); -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } - } +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(93897); -var import_slurpFile3 = __nccwpck_require__(69545); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true }; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: /* @__PURE__ */ __name((commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, "applyToStack") + }; +} +__name(getSerdePlugin, "getSerdePlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -80853,33 +70786,8 @@ var externalDataInterceptor = { /***/ }), -/***/ 69545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; - - -/***/ }), - -/***/ 54387: -/***/ ((module) => { +/***/ 62021: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -80903,113 +70811,87 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + loadConfig: () => loadConfig }); module.exports = __toCommonJS(index_exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); +// src/configLoader.ts -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +// src/fromEnv.ts +var import_property_provider = __nccwpck_require__(64181); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); +// src/getSelectorName.ts +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } catch (e) { + return functionString; } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +} +__name(getSelectorName, "getSelectorName"); + +// src/fromEnv.ts +var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === void 0) { + throw new Error(); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); + return config; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, + { logger: options?.logger } + ); + } +}, "fromEnv"); -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); +// src/fromSharedConfigFiles.ts -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); +var import_shared_ini_file_loader = __nccwpck_require__(30489); +var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = (0, import_shared_ini_file_loader.getProfileName)(init); + const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === void 0) { + throw new Error(); + } + return configValue; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, + { logger: init.logger } + ); + } +}, "fromSharedConfigFiles"); -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; +// src/fromStatic.ts -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); +var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +// src/configLoader.ts +var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + fromEnv(environmentVariableSelector, envOptions), + fromSharedConfigFiles(configFileSelector, configuration), + fromStatic(defaultValue) + ) + ); +}, "loadConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -81018,14 +70900,14 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 83068: +/***/ 82764: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -81040,459 +70922,1216 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - ConditionObject: () => import_util_endpoints.ConditionObject, - DeprecatedObject: () => import_util_endpoints.DeprecatedObject, - EndpointError: () => import_util_endpoints.EndpointError, - EndpointObject: () => import_util_endpoints.EndpointObject, - EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, - EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, - EndpointParams: () => import_util_endpoints.EndpointParams, - EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, - EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, - ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, - EvaluateOptions: () => import_util_endpoints.EvaluateOptions, - Expression: () => import_util_endpoints.Expression, - FunctionArgv: () => import_util_endpoints.FunctionArgv, - FunctionObject: () => import_util_endpoints.FunctionObject, - FunctionReturn: () => import_util_endpoints.FunctionReturn, - ParameterObject: () => import_util_endpoints.ParameterObject, - ReferenceObject: () => import_util_endpoints.ReferenceObject, - ReferenceRecord: () => import_util_endpoints.ReferenceRecord, - RuleSetObject: () => import_util_endpoints.RuleSetObject, - RuleSetRules: () => import_util_endpoints.RuleSetRules, - TreeRuleObject: () => import_util_endpoints.TreeRuleObject, - awsEndpointFunctions: () => awsEndpointFunctions, - getUserAgentPrefix: () => getUserAgentPrefix, - isIpAddress: () => import_util_endpoints.isIpAddress, - partition: () => partition, - resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, - resolveEndpoint: () => import_util_endpoints.resolveEndpoint, - setPartitionInfo: () => setPartitionInfo, - toEndpointV1: () => toEndpointV1, - useDefaultPartitionInfo: () => useDefaultPartitionInfo + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(index_exports); -// src/aws.ts +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(20843); +var import_querystring_builder = __nccwpck_require__(14959); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; -// src/lib/aws/isVirtualHostableS3Bucket.ts +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}, "getTransformedHeaders"); +// src/timing.ts +var timing = { + setTimeout: /* @__PURE__ */ __name((cb, ms) => setTimeout(cb, ms), "setTimeout"), + clearTimeout: /* @__PURE__ */ __name((timeoutId) => clearTimeout(timeoutId), "clearTimeout") +}; -// src/lib/isIpAddress.ts -var import_util_endpoints = __nccwpck_require__(79674); +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + static { + __name(this, "NodeHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/node-http2-handler.ts + + +var import_http22 = __nccwpck_require__(85675); + +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); + +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; + } + static { + __name(this, "NodeHttp2ConnectionPool"); + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } +}; -// src/lib/aws/isVirtualHostableS3Bucket.ts -var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + static { + __name(this, "NodeHttp2ConnectionManager"); + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; } } - return true; + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); + } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - if (!(0, import_util_endpoints.isValidHostLabel)(value)) { - return false; + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); } - if (value.length < 3 || value.length > 63) { - return false; + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); } - if (value !== value.toLowerCase()) { - return false; + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } } - if ((0, import_util_endpoints.isIpAddress)(value)) { - return false; + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; } - return true; -}, "isVirtualHostableS3Bucket"); - -// src/lib/aws/parseArn.ts -var ARN_DELIMITER = ":"; -var RESOURCE_DELIMITER = "/"; -var parseArn = /* @__PURE__ */ __name((value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; -}, "parseArn"); + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } +}; -// src/lib/aws/partitions.json -var partitions_default = { - partitions: [{ - id: "aws", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-east-1", - name: "aws", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "ap-northeast-1": { - description: "Asia Pacific (Tokyo)" - }, - "ap-northeast-2": { - description: "Asia Pacific (Seoul)" - }, - "ap-northeast-3": { - description: "Asia Pacific (Osaka)" - }, - "ap-south-1": { - description: "Asia Pacific (Mumbai)" - }, - "ap-south-2": { - description: "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1": { - description: "Asia Pacific (Singapore)" - }, - "ap-southeast-2": { - description: "Asia Pacific (Sydney)" - }, - "ap-southeast-3": { - description: "Asia Pacific (Jakarta)" - }, - "ap-southeast-4": { - description: "Asia Pacific (Melbourne)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-6": { - description: "Asia Pacific (New Zealand)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "aws global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "eu-central-1": { - description: "Europe (Frankfurt)" - }, - "eu-central-2": { - description: "Europe (Zurich)" - }, - "eu-north-1": { - description: "Europe (Stockholm)" - }, - "eu-south-1": { - description: "Europe (Milan)" - }, - "eu-south-2": { - description: "Europe (Spain)" - }, - "eu-west-1": { - description: "Europe (Ireland)" - }, - "eu-west-2": { - description: "Europe (London)" - }, - "eu-west-3": { - description: "Europe (Paris)" - }, - "il-central-1": { - description: "Israel (Tel Aviv)" - }, - "me-central-1": { - description: "Middle East (UAE)" - }, - "me-south-1": { - description: "Middle East (Bahrain)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "sa-east-1": { - description: "South America (Sao Paulo)" - }, - "us-east-1": { - description: "US East (N. Virginia)" - }, - "us-east-2": { - description: "US East (Ohio)" - }, - "us-west-1": { - description: "US West (N. California)" - }, - "us-west-2": { - description: "US West (Oregon)" +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); } + }); + } + static { + __name(this, "NodeHttp2Handler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - }, { - id: "aws-cn", - outputs: { - dnsSuffix: "amazonaws.com.cn", - dualStackDnsSuffix: "api.amazonwebservices.com.cn", - implicitGlobalRegion: "cn-northwest-1", - name: "aws-cn", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^cn\\-\\w+\\-\\d+$", - regions: { - "aws-cn-global": { - description: "aws-cn global region" - }, - "cn-north-1": { - description: "China (Beijing)" - }, - "cn-northwest-1": { - description: "China (Ningxia)" + return new _NodeHttp2Handler(instanceOrOptions); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } } - }, { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "api.amazonwebservices.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; } - } - }, { - id: "aws-iso", - outputs: { - dnsSuffix: "c2s.ic.gov", - dualStackDnsSuffix: "api.aws.ic.gov", - implicitGlobalRegion: "us-iso-east-1", - name: "aws-iso", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - regions: { - "aws-iso-global": { - description: "aws-iso global region" - }, - "us-iso-east-1": { - description: "US ISO East" - }, - "us-iso-west-1": { - description: "US ISO WEST" + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; } - } - }, { - id: "aws-iso-b", - outputs: { - dnsSuffix: "sc2s.sgov.gov", - dualStackDnsSuffix: "api.aws.scloud", - implicitGlobalRegion: "us-isob-east-1", - name: "aws-iso-b", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - regions: { - "aws-iso-b-global": { - description: "aws-iso-b global region" - }, - "us-isob-east-1": { - description: "US ISOB East (Ohio)" + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; } - } - }, { - id: "aws-iso-e", - outputs: { - dnsSuffix: "cloud.adc-e.uk", - dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", - implicitGlobalRegion: "eu-isoe-west-1", - name: "aws-iso-e", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", - regions: { - "aws-iso-e-global": { - description: "aws-iso-e global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" + if (request.fragment) { + path += `#${request.fragment}`; } - } - }, { - id: "aws-iso-f", - outputs: { - dnsSuffix: "csp.hci.ic.gov", - dualStackDnsSuffix: "api.aws.hci.ic.gov", - implicitGlobalRegion: "us-isof-south-1", - name: "aws-iso-f", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", - regions: { - "aws-iso-f-global": { - description: "aws-iso-f global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); } - } - }, { - id: "aws-us-gov", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-gov-west-1", - name: "aws-us-gov", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - regions: { - "aws-us-gov-global": { - description: "aws-us-gov global region" - }, - "us-gov-east-1": { - description: "AWS GovCloud (US-East)" - }, - "us-gov-west-1": { - description: "AWS GovCloud (US-West)" + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); } - }], - version: "1.1" + } }; -// src/lib/aws/partition.ts -var selectedPartitionsInfo = partitions_default; -var selectedUserAgentPrefix = ""; -var partition = /* @__PURE__ */ __name((value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } +// src/stream-collector/collector.ts + +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + static { + __name(this, "Collector"); + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +}; + +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; } + isDone = done; } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 64181: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize +}); +module.exports = __toCommonJS(index_exports); + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); - if (!DEFAULT_PARTITION) { - throw new Error( - "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist." - ); + static { + __name(this, "ProviderError"); } - return { - ...DEFAULT_PARTITION.outputs - }; -}, "partition"); -var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}, "setPartitionInfo"); -var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { - setPartitionInfo(partitions_default, ""); -}, "useDefaultPartitionInfo"); -var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +}; -// src/aws.ts -var awsEndpointFunctions = { - isVirtualHostableS3Bucket, - parseArn, - partition +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + static { + __name(this, "CredentialsProviderError"); + } }; -import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; -// src/resolveDefaultAwsRegionalEndpointsConfig.ts -var import_url_parser = __nccwpck_require__(67320); -var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - return toEndpointV1( - input.endpointProvider( - { - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: void 0 - }, - { logger: input.logger } - ) - ); + static { + __name(this, "TokenProviderError"); + } +}; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; }; } - return input; -}, "resolveDefaultAwsRegionalEndpointsConfig"); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: -// src/resolveEndpoint.ts +0 && (0); -// src/types/EndpointError.ts +/***/ }), -// src/types/EndpointRuleObject.ts +/***/ 20843: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/types/ErrorRuleObject.ts +// src/index.ts +var index_exports = {}; +__export(index_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(index_exports); +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); -// src/types/RuleSetObject.ts +// src/Field.ts +var import_types = __nccwpck_require__(65165); +var Field = class { + static { + __name(this, "Field"); + } + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; + } +}; +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); + } + /** + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. + */ + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + /** + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. + */ + getField(name) { + return this.entries[name.toLowerCase()]; + } + /** + * Delete entry from collection. + * + * @param name Name of the entry to delete. + */ + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + /** + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. + */ + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; -// src/types/TreeRuleObject.ts +// src/httpRequest.ts +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + /** + * Note: this does not deep-clone the body. + */ + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + /** + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. + */ + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); -// src/types/shared.ts +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +}; +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -81501,8 +72140,8 @@ var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.pa /***/ }), -/***/ 8776: -/***/ ((module) => { +/***/ 14959: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -81526,31 +72165,30 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - parseQueryString: () => parseQueryString + buildQueryString: () => buildQueryString }); module.exports = __toCommonJS(index_exports); -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); +var import_util_uri_escape = __nccwpck_require__(87377); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; } + parts.push(qsEntry); } } - return query; + return parts.join("&"); } -__name(parseQueryString, "parseQueryString"); +__name(buildQueryString, "buildQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -81559,8 +72197,8 @@ __name(parseQueryString, "parseQueryString"); /***/ }), -/***/ 67320: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 15183: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -81584,27 +72222,31 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - parseUrl: () => parseUrl + parseQueryString: () => parseQueryString }); module.exports = __toCommonJS(index_exports); -var import_querystring_parser = __nccwpck_require__(8776); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } + } } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); + return query; +} +__name(parseQueryString, "parseQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -81613,386 +72255,85 @@ var parseUrl = /* @__PURE__ */ __name((url) => { /***/ }), -/***/ 51656: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23327: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, - UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, - UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, - createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, - crtAvailability: () => crtAvailability, - defaultUserAgent: () => defaultUserAgent -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultUserAgent.ts -var import_os = __nccwpck_require__(70857); -var import_process = __nccwpck_require__(932); - -// src/crt-availability.ts -var crtAvailability = { - isCrtAvailable: false -}; - -// src/is-crt-available.ts -var isCrtAvailable = /* @__PURE__ */ __name(() => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}, "isCrtAvailable"); - -// src/defaultUserAgent.ts -var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - // sdk-metadata - ["aws-sdk-js", clientVersion], - // ua-metadata - ["ua", "2.1"], - // os-metadata - [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], - // language-metadata - // ECMAScript edition doesn't matter in JS, so no version needed. - ["lang/js"], - ["md/nodejs", `${import_process.versions.node}`] - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (import_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}, "createDefaultUserAgentProvider"); -var defaultUserAgent = createDefaultUserAgentProvider; - -// src/nodeAppIdConfigOptions.ts -var import_middleware_user_agent = __nccwpck_require__(32959); -var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -var NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), - default: import_middleware_user_agent.DEFAULT_UA_APP_ID -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 94274: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); - -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); - -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } - static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); - } + return "DEFAULT"; }; - -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } - static { - __name(this, "XmlNode"); - } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; - } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; }; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.getHomeDir = getHomeDir; /***/ }), -/***/ 37453: +/***/ 72412: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InvokeStore = void 0; -const async_hooks_1 = __nccwpck_require__(90290); -// AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA provides an escape hatch since we're modifying the global object which may not be expected to a customer's handler. -const noGlobalAwsLambda = process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "1" || - process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "true"; -if (!noGlobalAwsLambda) { - globalThis.awslambda = globalThis.awslambda || {}; -} -const PROTECTED_KEYS = { - REQUEST_ID: Symbol("_AWS_LAMBDA_REQUEST_ID"), - X_RAY_TRACE_ID: Symbol("_AWS_LAMBDA_X_RAY_TRACE_ID"), -}; -/** - * InvokeStore implementation class - */ -class InvokeStoreImpl { - static storage = new async_hooks_1.AsyncLocalStorage(); - // Protected keys for Lambda context fields - static PROTECTED_KEYS = PROTECTED_KEYS; - /** - * Initialize and run code within an invoke context - */ - static run(context, fn) { - return this.storage.run({ ...context }, fn); - } - /** - * Get the complete current context - */ - static getContext() { - return this.storage.getStore(); - } - /** - * Get a specific value from the context by key - */ - static get(key) { - const context = this.storage.getStore(); - return context?.[key]; - } - /** - * Set a custom value in the current context - * Protected Lambda context fields cannot be overwritten - */ - static set(key, value) { - if (this.isProtectedKey(key)) { - throw new Error(`Cannot modify protected Lambda context field`); - } - const context = this.storage.getStore(); - if (context) { - context[key] = value; - } - } - /** - * Get the current request ID - */ - static getRequestId() { - return this.get(this.PROTECTED_KEYS.REQUEST_ID) ?? "-"; - } - /** - * Get the current X-ray trace ID - */ - static getXRayTraceId() { - return this.get(this.PROTECTED_KEYS.X_RAY_TRACE_ID); - } - /** - * Check if we're currently within an invoke context - */ - static hasContext() { - return this.storage.getStore() !== undefined; - } - /** - * Check if a key is protected (readonly Lambda context field) - */ - static isProtectedKey(key) { - return (key === this.PROTECTED_KEYS.REQUEST_ID || - key === this.PROTECTED_KEYS.X_RAY_TRACE_ID); - } -} -let instance; -if (!noGlobalAwsLambda && globalThis.awslambda?.InvokeStore) { - instance = globalThis.awslambda.InvokeStore; -} -else { - instance = InvokeStoreImpl; - if (!noGlobalAwsLambda && globalThis.awslambda) { - globalThis.awslambda.InvokeStore = instance; +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(23327); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 27539: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(72412); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; } -} -exports.InvokeStore = instance; + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 39316: +/***/ 30489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -82012,196 +72353,201 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT, - CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT, - DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT, - DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT, - ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT, - ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT, - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, - NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getRegionInfo: () => getRegionInfo, - resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig, - resolveEndpointsConfig: () => resolveEndpointsConfig, - resolveRegionConfig: () => resolveRegionConfig + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(23327), module.exports); -// src/endpointsConfig/NodeUseDualstackEndpointConfigOptions.ts -var import_util_config_provider = __nccwpck_require__(56716); -var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; -var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; -var DEFAULT_USE_DUALSTACK_ENDPOINT = false; -var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), - default: false -}; - -// src/endpointsConfig/NodeUseFipsEndpointConfigOptions.ts - -var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; -var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; -var DEFAULT_USE_FIPS_ENDPOINT = false; -var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), - default: false -}; +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/endpointsConfig/resolveCustomEndpointsConfig.ts -var import_util_middleware = __nccwpck_require__(42634); -var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => { - const { tls, endpoint, urlParser, useDualstackEndpoint } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), - isCustomEndpoint: true, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false) - }); -}, "resolveCustomEndpointsConfig"); +// src/index.ts +__reExport(index_exports, __nccwpck_require__(72412), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(27539); -// src/endpointsConfig/resolveEndpointsConfig.ts +// src/loadSharedConfigFiles.ts -// src/endpointsConfig/utils/getEndpointFromRegion.ts -var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => { - const { tls = true } = input; - const region = await input.region(); - const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); - if (!dnsHostRegex.test(region)) { - throw new Error("Invalid region in client config"); +// src/getConfigData.ts +var import_types = __nccwpck_require__(65165); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - const useDualstackEndpoint = await input.useDualstackEndpoint(); - const useFipsEndpoint = await input.useFipsEndpoint(); - const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; - if (!hostname) { - throw new Error("Cannot resolve hostname from client config"); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } } - return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); -}, "getEndpointFromRegion"); +), "getConfigData"); -// src/endpointsConfig/resolveEndpointsConfig.ts -var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => { - const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false); - const { endpoint, useFipsEndpoint, urlParser, tls } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), - isCustomEndpoint: !!endpoint, - useDualstackEndpoint - }); -}, "resolveEndpointsConfig"); +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(23327); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" -}; +// src/getCredentialsFilepath.ts -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); +var import_getHomeDir2 = __nccwpck_require__(23327); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(23327); -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } else { + currentSection = sectionName; } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } + } + return map; +}, "parseIni"); -// src/regionInfo/getHostnameFromVariants.ts -var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find( - ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack") -)?.hostname, "getHostnameFromVariants"); - -// src/regionInfo/getResolvedHostname.ts -var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname"); - -// src/regionInfo/getResolvedPartition.ts -var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition"); - -// src/regionInfo/getResolvedSigningRegion.ts -var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { - if (signingRegion) { - return signingRegion; - } else if (useFipsEndpoint) { - const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); - const regionRegexmatchArray = hostname.match(regionRegexJs); - if (regionRegexmatchArray) { - return regionRegexmatchArray[0].slice(1, -1); - } - } -}, "getResolvedSigningRegion"); - -// src/regionInfo/getRegionInfo.ts -var getRegionInfo = /* @__PURE__ */ __name((region, { - useFipsEndpoint = false, - useDualstackEndpoint = false, - signingService, - regionHash, - partitionHash -}) => { - const partition = getResolvedPartition(region, { partitionHash }); - const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; - const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; - const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); - const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); - const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); - if (hostname === void 0) { - throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); - } - const signingRegion = getResolvedSigningRegion(hostname, { - signingRegion: regionHash[resolvedRegion]?.signingRegion, - regionRegex: partitionHash[partition].regionRegex, - useFipsEndpoint - }); +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(47307); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); return { - partition, - signingService, - hostname, - ...signingRegion && { signingRegion }, - ...regionHash[resolvedRegion]?.signingService && { - signingService: regionHash[resolvedRegion].signingService - } + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] }; -}, "getRegionInfo"); +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(47307); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } + } + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); + +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(27539); +var import_slurpFile3 = __nccwpck_require__(47307); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; + } +}; // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -82210,7 +72556,32 @@ var getRegionInfo = /* @__PURE__ */ __name((region, { /***/ }), -/***/ 12588: +/***/ 47307: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 65165: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -82350,7 +72721,265 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 42634: +/***/ 60043: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + parseUrl: () => parseUrl +}); +module.exports = __toCommonJS(index_exports); +var import_querystring_parser = __nccwpck_require__(15183); +var parseUrl = /* @__PURE__ */ __name((url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = (0, import_querystring_parser.parseQueryString)(search); + } + return { + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query + }; +}, "parseUrl"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 95895: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(21266); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; + + +/***/ }), + +/***/ 72722: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(95895), module.exports); +__reExport(index_exports, __nccwpck_require__(97234), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 97234: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(21266); +const util_utf8_1 = __nccwpck_require__(46090); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; + + +/***/ }), + +/***/ 21266: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(index_exports); +var import_is_array_buffer = __nccwpck_require__(21109); +var import_buffer = __nccwpck_require__(20181); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 79916: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(index_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 99755: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -82381,7 +73010,7 @@ __export(index_exports, { module.exports = __toCommonJS(index_exports); // src/getSmithyContext.ts -var import_types = __nccwpck_require__(12588); +var import_types = __nccwpck_require__(65165); var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); // src/normalizeProvider.ts @@ -82398,561 +73027,506 @@ var normalizeProvider = /* @__PURE__ */ __name((input) => { /***/ }), -/***/ 40566: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 79241: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, - DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, - ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, - ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, - ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, - Endpoint: () => Endpoint, - fromContainerMetadata: () => fromContainerMetadata, - fromInstanceMetadata: () => fromInstanceMetadata, - getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, - httpRequest: () => httpRequest, - providerConfigFromInit: () => providerConfigFromInit -}); -module.exports = __toCommonJS(index_exports); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; -// src/fromContainerMetadata.ts -var import_url = __nccwpck_require__(87016); +/***/ }), -// src/remoteProvider/httpRequest.ts -var import_property_provider = __nccwpck_require__(42382); -var import_buffer = __nccwpck_require__(20181); -var import_http = __nccwpck_require__(58611); -function httpRequest(options) { - return new Promise((resolve, reject) => { - const req = (0, import_http.request)({ - method: "GET", - ...options, - // Node.js http module doesn't accept hostname with square brackets - // Refs: https://github.com/nodejs/node/issues/39738 - hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") - }); - req.on("error", (err) => { - reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); - req.destroy(); - }); - req.on("timeout", () => { - reject(new import_property_provider.ProviderError("TimeoutError from instance metadata service")); - req.destroy(); - }); - req.on("response", (res) => { - const { statusCode = 400 } = res; - if (statusCode < 200 || 300 <= statusCode) { - reject( - Object.assign(new import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) - ); - req.destroy(); - } - const chunks = []; - res.on("data", (chunk) => { - chunks.push(chunk); - }); - res.on("end", () => { - resolve(import_buffer.Buffer.concat(chunks)); - req.destroy(); - }); - }); - req.end(); - }); +/***/ 34778: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { } -__name(httpRequest, "httpRequest"); - -// src/remoteProvider/ImdsCredentials.ts -var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); -var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ - accessKeyId: creds.AccessKeyId, - secretAccessKey: creds.SecretAccessKey, - sessionToken: creds.Token, - expiration: new Date(creds.Expiration), - ...creds.AccountId && { accountId: creds.AccountId } -}), "fromImdsCredentials"); - -// src/remoteProvider/RemoteProviderInit.ts -var DEFAULT_TIMEOUT = 1e3; -var DEFAULT_MAX_RETRIES = 0; -var providerConfigFromInit = /* @__PURE__ */ __name(({ - maxRetries = DEFAULT_MAX_RETRIES, - timeout = DEFAULT_TIMEOUT -}) => ({ maxRetries, timeout }), "providerConfigFromInit"); - -// src/remoteProvider/retry.ts -var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { - let promise = toRetry(); - for (let i = 0; i < maxRetries; i++) { - promise = promise.catch(toRetry); - } - return promise; -}, "retry"); - -// src/fromContainerMetadata.ts -var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { - const { timeout, maxRetries } = providerConfigFromInit(init); - return () => retry(async () => { - const requestOptions = await getCmdsUri({ logger: init.logger }); - const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); - if (!isImdsCredentials(credsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger - }); - } - return fromImdsCredentials(credsResponse); - }, maxRetries); -}, "fromContainerMetadata"); -var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { - if (process.env[ENV_CMDS_AUTH_TOKEN]) { - options.headers = { - ...options.headers, - Authorization: process.env[ENV_CMDS_AUTH_TOKEN] - }; - } - const buffer = await httpRequest({ - ...options, - timeout - }); - return buffer.toString(); -}, "requestFromEcsImds"); -var CMDS_IP = "169.254.170.2"; -var GREENGRASS_HOSTS = { - localhost: true, - "127.0.0.1": true -}; -var GREENGRASS_PROTOCOLS = { - "http:": true, - "https:": true -}; -var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { - if (process.env[ENV_CMDS_RELATIVE_URI]) { - return { - hostname: CMDS_IP, - path: process.env[ENV_CMDS_RELATIVE_URI] - }; - } - if (process.env[ENV_CMDS_FULL_URI]) { - const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); - if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { - tryNextLink: false, - logger - }); +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 72116: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(72722); +const stream_1 = __nccwpck_require__(2203); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); } - if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { - tryNextLink: false, - logger - }); + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); } - return { - ...parsed, - port: parsed.port ? parseInt(parsed.port, 10) : void 0 - }; - } - throw new import_property_provider.CredentialsProviderError( - `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, - { - tryNextLink: false, - logger + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); } - ); -}, "getCmdsUri"); +} +exports.ChecksumStream = ChecksumStream; -// src/fromInstanceMetadata.ts +/***/ }), +/***/ 49158: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/error/InstanceMetadataV1FallbackError.ts +"use strict"; -var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { - constructor(message, tryNextLink = true) { - super(message, tryNextLink); - this.tryNextLink = tryNextLink; - this.name = "InstanceMetadataV1FallbackError"; - Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); - } - static { - __name(this, "InstanceMetadataV1FallbackError"); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(72722); +const stream_type_check_1 = __nccwpck_require__(37785); +const ChecksumStream_browser_1 = __nccwpck_require__(34778); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; }; +exports.createChecksumStream = createChecksumStream; -// src/utils/getInstanceMetadataEndpoint.ts -var import_node_config_provider = __nccwpck_require__(85744); -var import_url_parser = __nccwpck_require__(38118); -// src/config/Endpoint.ts -var Endpoint = /* @__PURE__ */ ((Endpoint2) => { - Endpoint2["IPv4"] = "http://169.254.169.254"; - Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; - return Endpoint2; -})(Endpoint || {}); +/***/ }), -// src/config/EndpointConfigOptions.ts -var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; -var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; -var ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[ENV_ENDPOINT_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_ENDPOINT_NAME], "configFileSelector"), - default: void 0 -}; +/***/ 32384: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/config/EndpointMode.ts -var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { - EndpointMode2["IPv4"] = "IPv4"; - EndpointMode2["IPv6"] = "IPv6"; - return EndpointMode2; -})(EndpointMode || {}); - -// src/config/EndpointModeConfigOptions.ts -var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; -var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; -var ENDPOINT_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[ENV_ENDPOINT_MODE_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_ENDPOINT_MODE_NAME], "configFileSelector"), - default: "IPv4" /* IPv4 */ -}; - -// src/utils/getInstanceMetadataEndpoint.ts -var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); -var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); -var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { - const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); - switch (endpointMode) { - case "IPv4" /* IPv4 */: - return "http://169.254.169.254" /* IPv4 */; - case "IPv6" /* IPv6 */: - return "http://[fd00:ec2::254]" /* IPv6 */; - default: - throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); - } -}, "getFromEndpointModeConfig"); - -// src/utils/getExtendedInstanceMetadataCredentials.ts -var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; -var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; -var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; -var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { - const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); - const newExpiration = new Date(Date.now() + refreshInterval * 1e3); - logger.warn( - `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. -For more information, please visit: ` + STATIC_STABILITY_DOC_URL - ); - const originalExpiration = credentials.originalExpiration ?? credentials.expiration; - return { - ...credentials, - ...originalExpiration ? { originalExpiration } : {}, - expiration: newExpiration - }; -}, "getExtendedInstanceMetadataCredentials"); - -// src/utils/staticStabilityProvider.ts -var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { - const logger = options?.logger || console; - let pastCredentials; - return async () => { - let credentials; - try { - credentials = await provider(); - if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { - credentials = getExtendedInstanceMetadataCredentials(credentials, logger); - } - } catch (e) { - if (pastCredentials) { - logger.warn("Credential renew failed: ", e); - credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); - } else { - throw e; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(37785); +const ChecksumStream_1 = __nccwpck_require__(72116); +const createChecksumStream_browser_1 = __nccwpck_require__(49158); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); } - pastCredentials = credentials; - return credentials; - }; -}, "staticStabilityProvider"); - -// src/fromInstanceMetadata.ts -var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; -var IMDS_TOKEN_PATH = "/latest/api/token"; -var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; -var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; -var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; -var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); -var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { - let disableFetchToken = false; - const { logger, profile } = init; - const { timeout, maxRetries } = providerConfigFromInit(init); - const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { - const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; - if (isImdsV1Fallback) { - let fallbackBlockedFromProfile = false; - let fallbackBlockedFromProcessEnv = false; - const configValue = await (0, import_node_config_provider.loadConfig)( - { - environmentVariableSelector: /* @__PURE__ */ __name((env) => { - const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; - if (envValue === void 0) { - throw new import_property_provider.CredentialsProviderError( - `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, - { logger: init.logger } - ); - } - return fallbackBlockedFromProcessEnv; - }, "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile2) => { - const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; - return fallbackBlockedFromProfile; - }, "configFileSelector"), - default: false - }, - { - profile - } - )(); - if (init.ec2MetadataV1Disabled || configValue) { - const causes = []; - if (init.ec2MetadataV1Disabled) - causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); - if (fallbackBlockedFromProfile) causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); - if (fallbackBlockedFromProcessEnv) - causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); - throw new InstanceMetadataV1FallbackError( - `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( - ", " - )}].` - ); - } + return new ChecksumStream_1.ChecksumStream(init); +} + + +/***/ }), + +/***/ 40260: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(57075); +const ByteArrayCollector_1 = __nccwpck_require__(79241); +const createBufferedReadableStream_1 = __nccwpck_require__(34335); +const stream_type_check_1 = __nccwpck_require__(37785); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); } - const imdsProfile = (await retry(async () => { - let profile2; - try { - profile2 = await getProfile(options); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; } - throw err; - } - return profile2; - }, maxRetries2)).trim(); - return retry(async () => { - let creds; - try { - creds = await getCredentialsFromProfile(imdsProfile, options, init); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; - } - return creds; - }, maxRetries2); - }, "getCredentials"); - return async () => { - const endpoint = await getInstanceMetadataEndpoint(); - if (disableFetchToken) { - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } else { - let token; - try { - token = (await getMetadataToken({ ...endpoint, timeout })).toString(); - } catch (error) { - if (error?.statusCode === 400) { - throw Object.assign(error, { - message: "EC2 Metadata token request returned error" - }); - } else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { - disableFetchToken = true; + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } } - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } - return getCredentials(maxRetries, { - ...endpoint, - headers: { - [X_AWS_EC2_METADATA_TOKEN]: token - }, - timeout - }); - } - }; -}, "getInstanceMetadataProvider"); -var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ - ...options, - path: IMDS_TOKEN_PATH, - method: "PUT", - headers: { - "x-aws-ec2-metadata-token-ttl-seconds": "21600" - } -}), "getMetadataToken"); -var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); -var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { - const credentialsResponse = JSON.parse( - (await httpRequest({ - ...options, - path: IMDS_PATH + profile - })).toString() - ); - if (!isImdsCredentials(credentialsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger }); - } - return fromImdsCredentials(credentialsResponse); -}, "getCredentialsFromProfile"); -// Annotate the CommonJS export names for ESM import in node: + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} -0 && (0); +/***/ }), + +/***/ 34335: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(79241); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} /***/ }), -/***/ 85744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 22505: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(index_exports); +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; -// src/configLoader.ts +/***/ }), -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(42382); +/***/ 45139: +/***/ ((__unused_webpack_module, exports) => { -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } -} -__name(getSelectorName, "getSelectorName"); +"use strict"; -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); - } -}, "fromEnv"); - -// src/fromSharedConfigFiles.ts - -var import_shared_ini_file_loader = __nccwpck_require__(38924); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); + return collected; +} -// src/fromStatic.ts -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +/***/ }), -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 86901: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2203); +const headStream_browser_1 = __nccwpck_require__(45139); +const stream_type_check_1 = __nccwpck_require__(37785); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); +}; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} /***/ }), -/***/ 42382: -/***/ ((module) => { +/***/ 64691: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -82971,148 +73545,77 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter }); module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(72722); +var import_util_utf8 = __nccwpck_require__(46090); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); + } + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); } + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); + +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { static { - __name(this, "ProviderError"); + __name(this, "Uint8ArrayBlobAdapter"); } /** - * @deprecated use new operator. + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } } -}; - -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { /** - * @override + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; } -}; - -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { /** - * @override + * @param encoding - default 'utf-8'. + * @returns the blob as string. */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); } }; -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); - -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); +// src/index.ts +__reExport(index_exports, __nccwpck_require__(72116), module.exports); +__reExport(index_exports, __nccwpck_require__(32384), module.exports); +__reExport(index_exports, __nccwpck_require__(40260), module.exports); +__reExport(index_exports, __nccwpck_require__(22505), module.exports); +__reExport(index_exports, __nccwpck_require__(86901), module.exports); +__reExport(index_exports, __nccwpck_require__(76992), module.exports); +__reExport(index_exports, __nccwpck_require__(73423), module.exports); +__reExport(index_exports, __nccwpck_require__(37785), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -83121,144 +73624,212 @@ var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { /***/ }), -/***/ 39982: -/***/ ((module) => { +/***/ 65958: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - parseQueryString: () => parseQueryString -}); -module.exports = __toCommonJS(index_exports); -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(9136); +const util_base64_1 = __nccwpck_require__(72722); +const util_hex_encoding_1 = __nccwpck_require__(79916); +const util_utf8_1 = __nccwpck_require__(46090); +const stream_type_check_1 = __nccwpck_require__(37785); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } - } - return query; -} -__name(parseQueryString, "parseQueryString"); -// Annotate the CommonJS export names for ESM import in node: + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; -0 && (0); +/***/ }), + +/***/ 76992: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(82764); +const util_buffer_from_1 = __nccwpck_require__(21266); +const stream_1 = __nccwpck_require__(2203); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(65958); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; /***/ }), -/***/ 48660: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 16441: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(70857); -const path_1 = __nccwpck_require__(16928); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; + const readableStream = stream; + return readableStream.tee(); +} /***/ }), -/***/ 17669: +/***/ 73423: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(76982); -const path_1 = __nccwpck_require__(16928); -const getHomeDir_1 = __nccwpck_require__(48660); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2203); +const splitStream_browser_1 = __nccwpck_require__(16441); +const stream_type_check_1 = __nccwpck_require__(37785); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} /***/ }), -/***/ 88262: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 37785: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const fs_1 = __nccwpck_require__(79896); -const getSSOTokenFilepath_1 = __nccwpck_require__(17669); -const { readFile } = fs_1.promises; -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); }; -exports.getSSOTokenFromFile = getSSOTokenFromFile; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; /***/ }), -/***/ 38924: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 87377: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -83277,201 +73848,25 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(48660), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); - -// src/index.ts -__reExport(index_exports, __nccwpck_require__(17669), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(88262); - -// src/loadSharedConfigFiles.ts - - -// src/getConfigData.ts -var import_types = __nccwpck_require__(31242); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(48660); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(48660); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(48660); - -// src/parseIni.ts - -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } - } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(91550); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(91550); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); - -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } - } - } - return merged; -}, "mergeConfigFiles"); -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(88262); -var import_slurpFile3 = __nccwpck_require__(91550); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } -}; +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -83480,33 +73875,8 @@ var externalDataInterceptor = { /***/ }), -/***/ 91550: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); - } - return exports.filePromisesHash[path]; -}; -exports.slurpFile = slurpFile; - - -/***/ }), - -/***/ 31242: -/***/ ((module) => { +/***/ 46090: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -83530,113 +73900,41 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 }); module.exports = __toCommonJS(index_exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(21266); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; + return new Uint8Array(data); +}, "toUint8Array"); -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +// src/toUtf8.ts -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -83645,8 +73943,10 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 38118: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36463: +/***/ ((module) => { + +"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -83670,27 +73970,76 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - parseUrl: () => parseUrl + NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, + REGION_ENV_NAME: () => REGION_ENV_NAME, + REGION_INI_NAME: () => REGION_INI_NAME, + getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, + resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, + resolveRegionConfig: () => resolveRegionConfig }); module.exports = __toCommonJS(index_exports); -var import_querystring_parser = __nccwpck_require__(39982); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } + +// src/extensions/index.ts +var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + } }; -}, "parseUrl"); +}, "getAwsRegionExtensionConfiguration"); +var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; +}, "resolveAwsRegionExtensionConfiguration"); + +// src/regionConfig/config.ts +var REGION_ENV_NAME = "AWS_REGION"; +var REGION_INI_NAME = "region"; +var NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), + default: /* @__PURE__ */ __name(() => { + throw new Error("Region is missing"); + }, "default") +}; +var NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials" +}; + +// src/regionConfig/isFipsRegion.ts +var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); + +// src/regionConfig/getRealRegion.ts +var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); + +// src/regionConfig/resolveRegionConfig.ts +var resolveRegionConfig = /* @__PURE__ */ __name((input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: /* @__PURE__ */ __name(async () => { + if (typeof region === "string") { + return getRealRegion(region); + } + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, "region"), + useFipsEndpoint: /* @__PURE__ */ __name(async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, "useFipsEndpoint") + }); +}, "resolveRegionConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -83699,12 +74048,16 @@ var parseUrl = /* @__PURE__ */ __name((url) => { /***/ }), -/***/ 47809: +/***/ 75433: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -83719,218 +74072,214 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts -var src_exports = {}; -__export(src_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector +var index_exports = {}; +__export(index_exports, { + fromEnvSigningName: () => fromEnvSigningName, + fromSso: () => fromSso, + fromStatic: () => fromStatic, + nodeProvider: () => nodeProvider }); -module.exports = __toCommonJS(src_exports); +module.exports = __toCommonJS(index_exports); -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(72356); -var import_querystring_builder = __nccwpck_require__(18256); +// src/fromEnvSigningName.ts +var import_client = __nccwpck_require__(5152); +var import_httpAuthSchemes = __nccwpck_require__(97523); +var import_property_provider = __nccwpck_require__(51515); +var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); + } + const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); + if (!(bearerTokenKey in process.env)) { + throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); + } + const token = { token: process.env[bearerTokenKey] }; + (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}, "fromEnvSigningName"); -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); +// src/fromSso.ts -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var _FetchHttpHandler = class _FetchHttpHandler { - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); + +// src/constants.ts +var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; +var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +// src/getSsoOidcClient.ts +var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { + const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(89443))); + const ssoOidcClient = new SSOOIDCClient( + Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger + }) + ); + return ssoOidcClient; +}, "getSsoOidcClient"); + +// src/getNewSsoOidcToken.ts +var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { + const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(89443))); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); + return ssoOidcClient.send( + new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token" + }) + ); +}, "getNewSsoOidcToken"); + +// src/validateTokenExpiry.ts + +var validateTokenExpiry = /* @__PURE__ */ __name((token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); +}, "validateTokenExpiry"); + +// src/validateTokenKey.ts + +var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new import_property_provider.TokenProviderError( + `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, + false + ); + } +}, "validateTokenKey"); + +// src/writeSSOTokenToFile.ts +var import_shared_ini_file_loader = __nccwpck_require__(10751); +var import_fs = __nccwpck_require__(79896); +var { writeFile } = import_fs.promises; +var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { + const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}, "writeSSOTokenToFile"); + +// src/fromSso.ts +var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); +var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig } + }; + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } else if (!profile["sso_session"]) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); } - destroy() { + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new import_property_provider.TokenProviderError( + `Sso session '${ssoSessionName}' could not be found in shared credentials file.`, + false + ); } - async handle(request, { abortSignal } = {}) { - var _a; - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal == null ? void 0 : abortSignal.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if ((_a = this.config) == null ? void 0 : _a.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new import_property_provider.TokenProviderError( + `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, + false ); } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); + const ssoStartUrl = ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); + } catch (e) { + throw new import_property_provider.TokenProviderError( + `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, + false + ); } - httpHandlerConfigs() { - return this.config ?? {}; + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; } -}; -__name(_FetchHttpHandler, "FetchHttpHandler"); -var FetchHttpHandler = _FetchHttpHandler; - -// src/stream-collector.ts -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - var _a; - if (typeof Blob === "function" && stream instanceof Blob || ((_a = stream.constructor) == null ? void 0 : _a.name) === "Blob") { - return new Uint8Array(await stream.arrayBuffer()); + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { + validateTokenExpiry(existingToken); + return existingToken; } - return collectStream(stream); -}, "streamCollector"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken + }); + } catch (error) { } - isDone = done; + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration + }; + } catch (error) { + validateTokenExpiry(existingToken); + return existingToken; } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; +}, "fromSso"); + +// src/fromStatic.ts + +var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); } - return collected; -} -__name(collectStream, "collectStream"); + return token; +}, "fromStatic"); + +// src/nodeProvider.ts + +var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)(fromSso(init), async () => { + throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); + }), + (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, + (token) => token.expiration !== void 0 +), "nodeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -83939,8 +74288,8 @@ __name(collectStream, "collectStream"); /***/ }), -/***/ 5092: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51515: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -83964,45 +74313,143 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Hash: () => Hash + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(index_exports); -var import_util_buffer_from = __nccwpck_require__(34677); -var import_util_utf8 = __nccwpck_require__(82155); -var import_buffer = __nccwpck_require__(20181); -var import_crypto = __nccwpck_require__(76982); -var Hash = class { + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } static { - __name(this, "Hash"); + __name(this, "ProviderError"); + } + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } - constructor(algorithmIdentifier, secret) { - this.algorithmIdentifier = algorithmIdentifier; - this.secret = secret; - this.reset(); +}; + +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } - update(toHash, encoding) { - this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); + static { + __name(this, "CredentialsProviderError"); } - digest() { - return Promise.resolve(this.hash.digest()); +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - reset() { - this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); + static { + __name(this, "TokenProviderError"); } }; -function castSourceData(toCast, encoding) { - if (import_buffer.Buffer.isBuffer(toCast)) { - return toCast; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - if (typeof toCast === "string") { - return (0, import_util_buffer_from.fromString)(toCast, encoding); + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } } - if (ArrayBuffer.isView(toCast)) { - return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - return (0, import_util_buffer_from.fromArrayBuffer)(toCast); -} -__name(castSourceData, "castSourceData"); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}, "memoize"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -84011,95 +74458,85 @@ __name(castSourceData, "castSourceData"); /***/ }), -/***/ 68628: -/***/ ((module) => { +/***/ 11593: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +exports.getHomeDir = getHomeDir; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +/***/ }), +/***/ 77366: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -/***/ }), +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(11593); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; -/***/ 34677: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +/***/ }), -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(68628); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 93897: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(77366); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; +exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), -/***/ 82155: +/***/ 10751: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -84119,83 +74556,201 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + SSOToken: () => import_getSSOTokenFromFile2.SSOToken, + externalDataInterceptor: () => externalDataInterceptor, + getProfileName: () => getProfileName, + getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(11593), module.exports); -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(34677); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); +// src/index.ts +__reExport(index_exports, __nccwpck_require__(77366), module.exports); +var import_getSSOTokenFromFile2 = __nccwpck_require__(93897); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(54387); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } } - return new Uint8Array(data); -}, "toUint8Array"); +), "getConfigData"); -// src/toUtf8.ts +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(16928); +var import_getHomeDir = __nccwpck_require__(11593); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(11593); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(11593); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(69545); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); -0 && (0); +// src/getSsoSessionData.ts +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(69545); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); -/***/ }), +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } + } + return merged; +}, "mergeConfigFiles"); -/***/ 86130: -/***/ ((module) => { +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/externalDataInterceptor.ts +var import_getSSOTokenFromFile = __nccwpck_require__(93897); +var import_slurpFile3 = __nccwpck_require__(69545); +var externalDataInterceptor = { + getFileRecord() { + return import_slurpFile3.fileIntercept; + }, + interceptFile(path, contents) { + import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return import_getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + import_getSSOTokenFromFile.tokenIntercept[id] = contents; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(src_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -84204,8 +74759,33 @@ var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "func /***/ }), -/***/ 47212: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 69545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; + } + if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 54387: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -84229,47 +74809,113 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - contentLengthMiddleware: () => contentLengthMiddleware, - contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, - getContentLengthPlugin: () => getContentLengthPlugin + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(86382); -var CONTENT_LENGTH_HEADER = "content-length"; -function contentLengthMiddleware(bodyLengthChecker) { - return (next) => async (args) => { - const request = args.request; - if (import_protocol_http.HttpRequest.isInstance(request)) { - const { body, headers } = request; - if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { - try { - const length = bodyLengthChecker(body); - request.headers = { - ...request.headers, - [CONTENT_LENGTH_HEADER]: String(length) - }; - } catch (error) { - } - } - } - return next({ - ...args, - request + +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); + +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), + checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } }; -} -__name(contentLengthMiddleware, "contentLengthMiddleware"); -var contentLengthMiddlewareOptions = { - step: "build", - tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], - name: "contentLengthMiddleware", - override: true -}; -var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); - }, "applyToStack") -}), "getContentLengthPlugin"); +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -84278,9 +74924,11 @@ var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ /***/ }), -/***/ 86382: +/***/ 83068: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -84303,233 +74951,454 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + ConditionObject: () => import_util_endpoints.ConditionObject, + DeprecatedObject: () => import_util_endpoints.DeprecatedObject, + EndpointError: () => import_util_endpoints.EndpointError, + EndpointObject: () => import_util_endpoints.EndpointObject, + EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, + EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, + EndpointParams: () => import_util_endpoints.EndpointParams, + EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, + EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, + ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, + EvaluateOptions: () => import_util_endpoints.EvaluateOptions, + Expression: () => import_util_endpoints.Expression, + FunctionArgv: () => import_util_endpoints.FunctionArgv, + FunctionObject: () => import_util_endpoints.FunctionObject, + FunctionReturn: () => import_util_endpoints.FunctionReturn, + ParameterObject: () => import_util_endpoints.ParameterObject, + ReferenceObject: () => import_util_endpoints.ReferenceObject, + ReferenceRecord: () => import_util_endpoints.ReferenceRecord, + RuleSetObject: () => import_util_endpoints.RuleSetObject, + RuleSetRules: () => import_util_endpoints.RuleSetRules, + TreeRuleObject: () => import_util_endpoints.TreeRuleObject, + awsEndpointFunctions: () => awsEndpointFunctions, + getUserAgentPrefix: () => getUserAgentPrefix, + isIpAddress: () => import_util_endpoints.isIpAddress, + partition: () => partition, + resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, + resolveEndpoint: () => import_util_endpoints.resolveEndpoint, + setPartitionInfo: () => setPartitionInfo, + toEndpointV1: () => toEndpointV1, + useDefaultPartitionInfo: () => useDefaultPartitionInfo }); module.exports = __toCommonJS(index_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); +// src/aws.ts -// src/Field.ts -var import_types = __nccwpck_require__(12276); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); +// src/lib/aws/isVirtualHostableS3Bucket.ts + + +// src/lib/isIpAddress.ts +var import_util_endpoints = __nccwpck_require__(79674); + +// src/lib/aws/isVirtualHostableS3Bucket.ts +var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; + if (!(0, import_util_endpoints.isValidHostLabel)(value)) { + return false; } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; + if (value.length < 3 || value.length > 63) { + return false; } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + if (value !== value.toLowerCase()) { + return false; } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); + if ((0, import_util_endpoints.isIpAddress)(value)) { + return false; } -}; + return true; +}, "isVirtualHostableS3Bucket"); -// src/httpRequest.ts +// src/lib/aws/parseArn.ts +var ARN_DELIMITER = ":"; +var RESOURCE_DELIMITER = "/"; +var parseArn = /* @__PURE__ */ __name((value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) return null; + const [arn, partition2, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region, + accountId, + resourceId + }; +}, "parseArn"); -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); +// src/lib/aws/partitions.json +var partitions_default = { + partitions: [{ + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } + } + }, { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + } + } + }, { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + }], + version: "1.1" +}; + +// src/lib/aws/partition.ts +var selectedPartitionsInfo = partitions_default; +var selectedUserAgentPrefix = ""; +var partition = /* @__PURE__ */ __name((value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition2 of partitions) { + const { regions, outputs } = partition2; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } } - return cloned; } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + for (const partition2 of partitions) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); + const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error( + "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist." + ); } + return { + ...DEFAULT_PARTITION.outputs + }; +}, "partition"); +var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}, "setPartitionInfo"); +var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { + setPartitionInfo(partitions_default, ""); +}, "useDefaultPartitionInfo"); +var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); + +// src/aws.ts +var awsEndpointFunctions = { + isVirtualHostableS3Bucket, + parseArn, + partition }; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); +import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; +// src/resolveDefaultAwsRegionalEndpointsConfig.ts +var import_url_parser = __nccwpck_require__(67320); +var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + return toEndpointV1( + input.endpointProvider( + { + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: void 0 + }, + { logger: input.logger } + ) + ); + }; } -}; + return input; +}, "resolveDefaultAwsRegionalEndpointsConfig"); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); + +// src/resolveEndpoint.ts + + +// src/types/EndpointError.ts + + +// src/types/EndpointRuleObject.ts + + +// src/types/ErrorRuleObject.ts + + +// src/types/RuleSetObject.ts + + +// src/types/TreeRuleObject.ts + + +// src/types/shared.ts -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -84538,7 +75407,7 @@ __name(isValidHostname, "isValidHostname"); /***/ }), -/***/ 12276: +/***/ 8776: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -84563,113 +75432,31 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + parseQueryString: () => parseQueryString }); module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); + } + return query; +} +__name(parseQueryString, "parseQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -84678,7 +75465,7 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 19618: +/***/ 67320: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -84703,372 +75490,27 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, - CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, - ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, - ENV_RETRY_MODE: () => ENV_RETRY_MODE, - NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, - NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, - StandardRetryStrategy: () => StandardRetryStrategy, - defaultDelayDecider: () => defaultDelayDecider, - defaultRetryDecider: () => defaultRetryDecider, - getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, - getRetryAfterHint: () => getRetryAfterHint, - getRetryPlugin: () => getRetryPlugin, - omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, - omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, - resolveRetryConfig: () => resolveRetryConfig, - retryMiddleware: () => retryMiddleware, - retryMiddlewareOptions: () => retryMiddlewareOptions + parseUrl: () => parseUrl }); module.exports = __toCommonJS(index_exports); - -// src/AdaptiveRetryStrategy.ts - - -// src/StandardRetryStrategy.ts -var import_protocol_http = __nccwpck_require__(64864); - - -var import_uuid = __nccwpck_require__(12048); - -// src/defaultRetryQuota.ts -var import_util_retry = __nccwpck_require__(15518); -var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { - const MAX_CAPACITY = initialRetryTokens; - const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; - const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; - const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; - let availableCapacity = initialRetryTokens; - const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); - const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); - const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { - if (!hasRetryTokens(error)) { - throw new Error("No retry token available"); - } - const capacityAmount = getCapacityAmount(error); - availableCapacity -= capacityAmount; - return capacityAmount; - }, "retrieveRetryTokens"); - const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { - availableCapacity += capacityReleaseAmount ?? noRetryIncrement; - availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); - }, "releaseRetryTokens"); - return Object.freeze({ - hasRetryTokens, - retrieveRetryTokens, - releaseRetryTokens - }); -}, "getDefaultRetryQuota"); - -// src/delayDecider.ts - -var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); - -// src/retryDecider.ts -var import_service_error_classification = __nccwpck_require__(42058); -var defaultRetryDecider = /* @__PURE__ */ __name((error) => { - if (!error) { - return false; - } - return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); -}, "defaultRetryDecider"); - -// src/util.ts -var asSdkError = /* @__PURE__ */ __name((error) => { - if (error instanceof Error) return error; - if (error instanceof Object) return Object.assign(new Error(), error); - if (typeof error === "string") return new Error(error); - return new Error(`AWS SDK error wrapper for ${error}`); -}, "asSdkError"); - -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = import_util_retry.RETRY_MODES.STANDARD; - this.retryDecider = options?.retryDecider ?? defaultRetryDecider; - this.delayDecider = options?.delayDecider ?? defaultDelayDecider; - this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); - } - static { - __name(this, "StandardRetryStrategy"); - } - shouldRetry(error, attempts, maxAttempts) { - return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); - } - async getMaxAttempts() { - let maxAttempts; - try { - maxAttempts = await this.maxAttemptsProvider(); - } catch (error) { - maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS; - } - return maxAttempts; - } - async retry(next, args, options) { - let retryTokenAmount; - let attempts = 0; - let totalDelay = 0; - const maxAttempts = await this.getMaxAttempts(); - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); - } - while (true) { - try { - if (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - if (options?.beforeRequest) { - await options.beforeRequest(); - } - const { response, output } = await next(args); - if (options?.afterRequest) { - options.afterRequest(response); - } - this.retryQuota.releaseRetryTokens(retryTokenAmount); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalDelay; - return { response, output }; - } catch (e) { - const err = asSdkError(e); - attempts++; - if (this.shouldRetry(err, attempts, maxAttempts)) { - retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); - const delayFromDecider = this.delayDecider( - (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.DEFAULT_RETRY_DELAY_BASE, - attempts - ); - const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); - const delay = Math.max(delayFromResponse || 0, delayFromDecider); - totalDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - continue; - } - if (!err.$metadata) { - err.$metadata = {}; - } - err.$metadata.attempts = attempts; - err.$metadata.totalRetryDelay = totalDelay; - throw err; - } - } - } -}; -var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.HttpResponse.isInstance(response)) return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) return retryAfterSeconds * 1e3; - const retryAfterDate = new Date(retryAfter); - return retryAfterDate.getTime() - Date.now(); -}, "getDelayFromRetryAfterHeader"); - -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "AdaptiveRetryStrategy"); - } - constructor(maxAttemptsProvider, options) { - const { rateLimiter, ...superOptions } = options ?? {}; - super(maxAttemptsProvider, superOptions); - this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); - this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; - } - async retry(next, args) { - return super.retry(next, args, { - beforeRequest: /* @__PURE__ */ __name(async () => { - return this.rateLimiter.getSendToken(); - }, "beforeRequest"), - afterRequest: /* @__PURE__ */ __name((response) => { - this.rateLimiter.updateClientSendingRate(response); - }, "afterRequest") - }); +var import_querystring_parser = __nccwpck_require__(8776); +var parseUrl = /* @__PURE__ */ __name((url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); } -}; - -// src/configurations.ts -var import_util_middleware = __nccwpck_require__(73976); - -var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; -var CONFIG_MAX_ATTEMPTS = "max_attempts"; -var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => { - const value = env[ENV_MAX_ATTEMPTS]; - if (!value) return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => { - const value = profile[CONFIG_MAX_ATTEMPTS]; - if (!value) return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, "configFileSelector"), - default: import_util_retry.DEFAULT_MAX_ATTEMPTS -}; -var resolveRetryConfig = /* @__PURE__ */ __name((input) => { - const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; - const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); - return Object.assign(input, { - maxAttempts, - retryStrategy: /* @__PURE__ */ __name(async () => { - if (retryStrategy) { - return retryStrategy; - } - const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); - if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { - return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); - } - return new import_util_retry.StandardRetryStrategy(maxAttempts); - }, "retryStrategy") - }); -}, "resolveRetryConfig"); -var ENV_RETRY_MODE = "AWS_RETRY_MODE"; -var CONFIG_RETRY_MODE = "retry_mode"; -var NODE_RETRY_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[ENV_RETRY_MODE], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[CONFIG_RETRY_MODE], "configFileSelector"), - default: import_util_retry.DEFAULT_RETRY_MODE -}; - -// src/omitRetryHeadersMiddleware.ts - - -var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; - delete request.headers[import_util_retry.REQUEST_HEADER]; + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = (0, import_querystring_parser.parseQueryString)(search); } - return next(args); -}, "omitRetryHeadersMiddleware"); -var omitRetryHeadersMiddlewareOptions = { - name: "omitRetryHeadersMiddleware", - tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true -}; -var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); - }, "applyToStack") -}), "getOmitRetryHeadersPlugin"); - -// src/retryMiddleware.ts - - -var import_smithy_client = __nccwpck_require__(61411); - - -var import_isStreamingPayload = __nccwpck_require__(49831); -var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - let retryStrategy = await options.retryStrategy(); - const maxAttempts = await options.maxAttempts(); - if (isRetryStrategyV2(retryStrategy)) { - retryStrategy = retryStrategy; - let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); - let lastError = new Error(); - let attempts = 0; - let totalRetryDelay = 0; - const { request } = args; - const isRequest = import_protocol_http.HttpRequest.isInstance(request); - if (isRequest) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); - } - while (true) { - try { - if (isRequest) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - const { response, output } = await next(args); - retryStrategy.recordSuccess(retryToken); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalRetryDelay; - return { response, output }; - } catch (e) { - const retryErrorInfo = getRetryErrorInfo(e); - lastError = asSdkError(e); - if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { - (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( - "An error was encountered in a non-retryable streaming request." - ); - throw lastError; - } - try { - retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); - } catch (refreshError) { - if (!lastError.$metadata) { - lastError.$metadata = {}; - } - lastError.$metadata.attempts = attempts + 1; - lastError.$metadata.totalRetryDelay = totalRetryDelay; - throw lastError; - } - attempts = retryToken.getRetryCount(); - const delay = retryToken.getRetryDelay(); - totalRetryDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - } else { - retryStrategy = retryStrategy; - if (retryStrategy?.mode) - context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; - return retryStrategy.retry(next, args); - } -}, "retryMiddleware"); -var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); -var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { - const errorInfo = { - error, - errorType: getRetryErrorType(error) + return { + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query }; - const retryAfterHint = getRetryAfterHint(error.$response); - if (retryAfterHint) { - errorInfo.retryAfterHint = retryAfterHint; - } - return errorInfo; -}, "getRetryErrorInfo"); -var getRetryErrorType = /* @__PURE__ */ __name((error) => { - if ((0, import_service_error_classification.isThrottlingError)(error)) return "THROTTLING"; - if ((0, import_service_error_classification.isTransientError)(error)) return "TRANSIENT"; - if ((0, import_service_error_classification.isServerError)(error)) return "SERVER_ERROR"; - return "CLIENT_ERROR"; -}, "getRetryErrorType"); -var retryMiddlewareOptions = { - name: "retryMiddleware", - tags: ["RETRY"], - step: "finalizeRequest", - priority: "high", - override: true -}; -var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(retryMiddleware(options), retryMiddlewareOptions); - }, "applyToStack") -}), "getRetryPlugin"); -var getRetryAfterHint = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.HttpResponse.isInstance(response)) return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) return new Date(retryAfterSeconds * 1e3); - const retryAfterDate = new Date(retryAfter); - return retryAfterDate; -}, "getRetryAfterHint"); +}, "parseUrl"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -85077,24 +75519,11 @@ var getRetryAfterHint = /* @__PURE__ */ __name((response) => { /***/ }), -/***/ 49831: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 51656: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isStreamingPayload = void 0; -const stream_1 = __nccwpck_require__(2203); -const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || - (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); -exports.isStreamingPayload = isStreamingPayload; - - -/***/ }), - -/***/ 64864: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -85117,233 +75546,252 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, + UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, + UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, + createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, + crtAvailability: () => crtAvailability, + defaultUserAgent: () => defaultUserAgent }); module.exports = __toCommonJS(index_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); +// src/defaultUserAgent.ts +var import_os = __nccwpck_require__(70857); +var import_process = __nccwpck_require__(932); + +// src/crt-availability.ts +var crtAvailability = { + isCrtAvailable: false +}; + +// src/is-crt-available.ts +var isCrtAvailable = /* @__PURE__ */ __name(() => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}, "isCrtAvailable"); + +// src/defaultUserAgent.ts +var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { + return async (config) => { + const sections = [ + // sdk-metadata + ["aws-sdk-js", clientVersion], + // ua-metadata + ["ua", "2.1"], + // os-metadata + [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], + // language-metadata + // ECMAScript edition doesn't matter in JS, so no version needed. + ["lang/js"], + ["md/nodejs", `${import_process.versions.node}`] + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); } + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (import_process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); + } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); +}, "createDefaultUserAgentProvider"); +var defaultUserAgent = createDefaultUserAgentProvider; -// src/Field.ts -var import_types = __nccwpck_require__(36158); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); +// src/nodeAppIdConfigOptions.ts +var import_middleware_user_agent = __nccwpck_require__(32959); +var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +var NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), + default: import_middleware_user_agent.DEFAULT_UA_APP_ID +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 94274: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + XmlNode: () => XmlNode, + XmlText: () => XmlText +}); +module.exports = __toCommonJS(index_exports); + +// src/escape-attribute.ts +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +__name(escapeAttribute, "escapeAttribute"); + +// src/escape-element.ts +function escapeElement(value) { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); +} +__name(escapeElement, "escapeElement"); + +// src/XmlText.ts +var XmlText = class { + constructor(value) { + this.value = value; } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + static { + __name(this, "XmlText"); } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; + return escapeElement("" + this.value); } }; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; +// src/XmlNode.ts +var XmlNode = class _XmlNode { + constructor(name, children = []) { + this.name = name; + this.children = children; } static { - __name(this, "Fields"); + __name(this, "XmlNode"); } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== void 0) { + node.withName(withName); + } + return node; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; } /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. + * @internal + * Alias of {@link XmlNode#withName(string)} for codegen brevity. */ - getField(name) { - return this.entries[name.toLowerCase()]; + n(name) { + this.name = name; + return this; } /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. + * @internal + * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + c(child) { + this.children.push(child); + return this; } /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. + * @internal + * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; } /** - * Note: this does not deep-clone the body. + * Create a child node. + * Used in serialization of string fields. + * @internal */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); } - return cloned; } /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. + * Creates list child nodes. + * @internal */ - static isInstance(request) { - if (!request) { - return false; + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + * Creates list child nodes with container. + * @internal */ - clone() { - return _HttpRequest.clone(this); - } -}; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; } }; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -85352,1098 +75800,1505 @@ __name(isValidHostname, "isValidHostname"); /***/ }), -/***/ 36158: -/***/ ((module) => { +/***/ 37453: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InvokeStore = void 0; +const async_hooks_1 = __nccwpck_require__(90290); +// AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA provides an escape hatch since we're modifying the global object which may not be expected to a customer's handler. +const noGlobalAwsLambda = process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "1" || + process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "true"; +if (!noGlobalAwsLambda) { + globalThis.awslambda = globalThis.awslambda || {}; +} +const PROTECTED_KEYS = { + REQUEST_ID: Symbol("_AWS_LAMBDA_REQUEST_ID"), + X_RAY_TRACE_ID: Symbol("_AWS_LAMBDA_X_RAY_TRACE_ID"), }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +/** + * InvokeStore implementation class + */ +class InvokeStoreImpl { + static storage = new async_hooks_1.AsyncLocalStorage(); + // Protected keys for Lambda context fields + static PROTECTED_KEYS = PROTECTED_KEYS; + /** + * Initialize and run code within an invoke context + */ + static run(context, fn) { + return this.storage.run({ ...context }, fn); + } + /** + * Get the complete current context + */ + static getContext() { + return this.storage.getStore(); + } + /** + * Get a specific value from the context by key + */ + static get(key) { + const context = this.storage.getStore(); + return context?.[key]; + } + /** + * Set a custom value in the current context + * Protected Lambda context fields cannot be overwritten + */ + static set(key, value) { + if (this.isProtectedKey(key)) { + throw new Error(`Cannot modify protected Lambda context field`); + } + const context = this.storage.getStore(); + if (context) { + context[key] = value; + } + } + /** + * Get the current request ID + */ + static getRequestId() { + return this.get(this.PROTECTED_KEYS.REQUEST_ID) ?? "-"; + } + /** + * Get the current X-ray trace ID + */ + static getXRayTraceId() { + return this.get(this.PROTECTED_KEYS.X_RAY_TRACE_ID); + } + /** + * Check if we're currently within an invoke context + */ + static hasContext() { + return this.storage.getStore() !== undefined; + } + /** + * Check if a key is protected (readonly Lambda context field) + */ + static isProtectedKey(key) { + return (key === this.PROTECTED_KEYS.REQUEST_ID || + key === this.PROTECTED_KEYS.X_RAY_TRACE_ID); + } +} +let instance; +if (!noGlobalAwsLambda && globalThis.awslambda?.InvokeStore) { + instance = globalThis.awslambda.InvokeStore; +} +else { + instance = InvokeStoreImpl; + if (!noGlobalAwsLambda && globalThis.awslambda) { + globalThis.awslambda.InvokeStore = instance; + } +} +exports.InvokeStore = instance; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); +/***/ }), -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +/***/ 39316: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +"use strict"; -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") + +var utilConfigProvider = __nccwpck_require__(56716); +var utilMiddleware = __nccwpck_require__(42634); + +const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +const DEFAULT_USE_DUALSTACK_ENDPOINT = false; +const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, +}; + +const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +const DEFAULT_USE_FIPS_ENDPOINT = false; +const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, +}; + +const resolveCustomEndpointsConfig = (input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") +}; + +const getEndpointFromRegion = async (input) => { + const { tls = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}; + +const resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint + ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) + : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint, }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); +}; + +const REGION_ENV_NAME = "AWS_REGION"; +const REGION_INI_NAME = "region"; +const NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: () => { + throw new Error("Region is missing"); }, - checksumAlgorithms() { - return checksumAlgorithms; +}; +const NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials", +}; + +const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); + +const getRealRegion = (region) => isFipsRegion(region) + ? ["fips-aws-global", "aws-fips"].includes(region) + ? "us-east-1" + : region.replace(/fips-(dkr-|prod-)?|-fips/, "") + : region; + +const resolveRegionConfig = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); + return Object.assign(input, { + region: async () => { + if (typeof region === "string") { + return getRealRegion(region); + } + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, + }); +}; -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); +const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); +const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname + ? regionHostname + : partitionHostname + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; +const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; + +const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; + } + else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } + } +}; + +const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === undefined) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + } + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint, + }); + return { + partition, + signingService, + hostname, + ...(signingRegion && { signingRegion }), + ...(regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService, + }), + }; +}; -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; +exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; +exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; +exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; +exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; +exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; +exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.getRegionInfo = getRegionInfo; +exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; +exports.resolveEndpointsConfig = resolveEndpointsConfig; +exports.resolveRegionConfig = resolveRegionConfig; -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +/***/ }), +/***/ 12588: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -/***/ }), -/***/ 73976: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(index_exports); +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(36158); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); +const SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); -0 && (0); +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), -/***/ 9208: -/***/ ((module) => { +/***/ 42634: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +"use strict"; + + +var types = __nccwpck_require__(12588); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - constructStack: () => constructStack +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; + + +/***/ }), + +/***/ 40566: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var propertyProvider = __nccwpck_require__(42382); +var url = __nccwpck_require__(87016); +var buffer = __nccwpck_require__(20181); +var http = __nccwpck_require__(58611); +var nodeConfigProvider = __nccwpck_require__(85744); +var urlParser = __nccwpck_require__(38118); + +function httpRequest(options) { + return new Promise((resolve, reject) => { + const req = http.request({ + method: "GET", + ...options, + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1"), + }); + req.on("error", (err) => { + reject(Object.assign(new propertyProvider.ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new propertyProvider.ProviderError("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || 300 <= statusCode) { + reject(Object.assign(new propertyProvider.ProviderError("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve(buffer.Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); +} + +const isImdsCredentials = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.AccessKeyId === "string" && + typeof arg.SecretAccessKey === "string" && + typeof arg.Token === "string" && + typeof arg.Expiration === "string"; +const fromImdsCredentials = (creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...(creds.AccountId && { accountId: creds.AccountId }), }); -module.exports = __toCommonJS(src_exports); -// src/MiddlewareStack.ts -var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); - } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); - } - } - return _aliases; -}, "getAllAliases"); -var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; -}, "getMiddlewareNameWithAliases"); -var constructStack = /* @__PURE__ */ __name(() => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = /* @__PURE__ */ new Set(); - const sort = /* @__PURE__ */ __name((entries) => entries.sort( - (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] - ), "sort"); - const removeByName = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const aliases = getAllAliases(entry.name, entry.aliases); - if (aliases.includes(toRemove)) { - isRemoved = true; - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByName"); - const removeByReference = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByReference"); - const cloneTo = /* @__PURE__ */ __name((toStack) => { - var _a; - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - (_a = toStack.identifyOnResolve) == null ? void 0 : _a.call(toStack, stack.identifyOnResolve()); - return toStack; - }, "cloneTo"); - const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { - const expandedMiddlewareList = []; - from.before.forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - expandedMiddlewareList.push(from); - from.after.reverse().forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - return expandedMiddlewareList; - }, "expandRelativeMiddlewareList"); - const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { - const normalizedAbsoluteEntries = []; - const normalizedRelativeEntries = []; - const normalizedEntriesNameMap = {}; - absoluteEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedAbsoluteEntries.push(normalizedEntry); - }); - relativeEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedRelativeEntries.push(normalizedEntry); - }); - normalizedRelativeEntries.forEach((entry) => { - if (entry.toMiddleware) { - const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; - if (toMiddleware === void 0) { - if (debug) { - return; - } - throw new Error( - `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` - ); - } - if (entry.relation === "after") { - toMiddleware.after.push(entry); - } - if (entry.relation === "before") { - toMiddleware.before.push(entry); +const DEFAULT_TIMEOUT = 1000; +const DEFAULT_MAX_RETRIES = 0; +const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout }); + +const retry = (toRetry, maxRetries) => { + let promise = toRetry(); + for (let i = 0; i < maxRetries; i++) { + promise = promise.catch(toRetry); + } + return promise; +}; + +const ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromContainerMetadata = (init = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); } - } + return fromImdsCredentials(credsResponse); + }, maxRetries); +}; +const requestFromEcsImds = async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN], + }; + } + const buffer = await httpRequest({ + ...options, + timeout, }); - const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce( - (wholeList, expandedMiddlewareList) => { - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, - [] - ); - return mainChain; - }, "getMiddlewareList"); - const stack = { - add: (middleware, options = {}) => { - const { name, override, aliases: _aliases } = options; - const entry = { - step: "initialize", - priority: "normal", - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = absoluteEntries.findIndex( - (entry2) => { - var _a; - return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); - } - ); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = absoluteEntries[toOverrideIndex]; - if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` - ); - } - absoluteEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - absoluteEntries.push(entry); - }, - addRelativeTo: (middleware, options) => { - const { name, override, aliases: _aliases } = options; - const entry = { - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = relativeEntries.findIndex( - (entry2) => { - var _a; - return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); - } - ); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = relativeEntries[toOverrideIndex]; - if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` - ); - } - relativeEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); + return buffer.toString(); +}; +const CMDS_IP = "169.254.170.2"; +const GREENGRASS_HOSTS = { + localhost: true, + "127.0.0.1": true, +}; +const GREENGRASS_PROTOCOLS = { + "http:": true, + "https:": true, +}; +const getCmdsUri = async ({ logger }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI], + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + const parsed = url.parse(process.env[ENV_CMDS_FULL_URI]); + if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger, + }); } - } - relativeEntries.push(entry); - }, - clone: () => cloneTo(constructStack()), - use: (plugin) => { - plugin.applyToStack(stack); - }, - remove: (toRemove) => { - if (typeof toRemove === "string") - return removeByName(toRemove); - else - return removeByReference(toRemove); - }, - removeByTag: (toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const { tags, name, aliases: _aliases } = entry; - if (tags && tags.includes(toRemove)) { - const aliases = getAllAliases(name, _aliases); - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - isRemoved = true; - return false; + if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger, + }); } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - var _a; - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve( - identifyOnResolve || cloned.identifyOnResolve() || (((_a = from.identifyOnResolve) == null ? void 0 : _a.call(from)) ?? false) - ); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? mw.relation + " " + mw.toMiddleware; - return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; - }); - }, - identifyOnResolve(toggle) { - if (typeof toggle === "boolean") - identifyOnResolve = toggle; - return identifyOnResolve; - }, - resolve: (handler, context) => { - for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { - handler = middleware(handler, context); - } - if (identifyOnResolve) { - console.log(stack.identify()); - } - return handler; + return { + ...parsed, + port: parsed.port ? parseInt(parsed.port, 10) : undefined, + }; } - }; - return stack; -}, "constructStack"); -var stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1 -}; -var priorityWeights = { - high: 3, - normal: 2, - low: 1 + throw new propertyProvider.CredentialsProviderError("The container metadata credential provider cannot be used unless" + + ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` + + " variable is set", { + tryNextLink: false, + logger, + }); }; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +class InstanceMetadataV1FallbackError extends propertyProvider.CredentialsProviderError { + tryNextLink; + name = "InstanceMetadataV1FallbackError"; + constructor(message, tryNextLink = true) { + super(message, tryNextLink); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); + } +} +exports.Endpoint = void 0; +(function (Endpoint) { + Endpoint["IPv4"] = "http://169.254.169.254"; + Endpoint["IPv6"] = "http://[fd00:ec2::254]"; +})(exports.Endpoint || (exports.Endpoint = {})); -/***/ }), +const ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; +const CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; +const ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: undefined, +}; -/***/ 61279: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var EndpointMode; +(function (EndpointMode) { + EndpointMode["IPv4"] = "IPv4"; + EndpointMode["IPv6"] = "IPv6"; +})(EndpointMode || (EndpointMode = {})); + +const ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; +const CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; +const ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: EndpointMode.IPv4, +}; + +const getInstanceMetadataEndpoint = async () => urlParser.parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig())); +const getFromEndpointConfig = async () => nodeConfigProvider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(); +const getFromEndpointModeConfig = async () => { + const endpointMode = await nodeConfigProvider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case EndpointMode.IPv4: + return exports.Endpoint.IPv4; + case EndpointMode.IPv6: + return exports.Endpoint.IPv6; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`); + } +}; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; +const STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; +const STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; +const getExtendedInstanceMetadataCredentials = (credentials, logger) => { + const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); + const newExpiration = new Date(Date.now() + refreshInterval * 1000); + logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + + `credentials will be attempted after ${new Date(newExpiration)}.\nFor more information, please visit: ` + + STATIC_STABILITY_DOC_URL); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...(originalExpiration ? { originalExpiration } : {}), + expiration: newExpiration, + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; + +const staticStabilityProvider = (provider, options = {}) => { + const logger = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger); + } + } + catch (e) { + if (pastCredentials) { + logger.warn("Credential renew failed: ", e); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } + else { + throw e; + } + } + pastCredentials = credentials; + return credentials; + }; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector +const IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; +const IMDS_TOKEN_PATH = "/latest/api/token"; +const AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; +const PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; +const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }); +const getInstanceMetadataProvider = (init = {}) => { + let disableFetchToken = false; + const { logger, profile } = init; + const { timeout, maxRetries } = providerConfigFromInit(init); + const getCredentials = async (maxRetries, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await nodeConfigProvider.loadConfig({ + environmentVariableSelector: (env) => { + const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === undefined) { + throw new propertyProvider.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger }); + } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile) => { + const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; + return fallbackBlockedFromProfile; + }, + default: false, + }, { + profile, + })(); + if (init.ec2MetadataV1Disabled || configValue) { + const causes = []; + if (init.ec2MetadataV1Disabled) + causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); + if (fallbackBlockedFromProfile) + causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); + if (fallbackBlockedFromProcessEnv) + causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); + throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); + } + } + const imdsProfile = (await retry(async () => { + let profile; + try { + profile = await getProfile(options); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return profile; + }, maxRetries)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return creds; + }, maxRetries); + }; + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + else { + let token; + try { + token = (await getMetadataToken({ ...endpoint, timeout })).toString(); + } + catch (error) { + if (error?.statusCode === 400) { + throw Object.assign(error, { + message: "EC2 Metadata token request returned error", + }); + } + else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { + disableFetchToken = true; + } + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + return getCredentials(maxRetries, { + ...endpoint, + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token, + }, + timeout, + }); + } + }; +}; +const getMetadataToken = async (options) => httpRequest({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600", + }, }); -module.exports = __toCommonJS(src_exports); +const getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(); +const getCredentialsFromProfile = async (profile, options, init) => { + const credentialsResponse = JSON.parse((await httpRequest({ + ...options, + path: IMDS_PATH + profile, + })).toString()); + if (!isImdsCredentials(credentialsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); + } + return fromImdsCredentials(credentialsResponse); +}; -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(72356); -var import_querystring_builder = __nccwpck_require__(18256); -var import_http = __nccwpck_require__(58611); -var import_https = __nccwpck_require__(65692); +exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; +exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; +exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; +exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; +exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; +exports.fromContainerMetadata = fromContainerMetadata; +exports.fromInstanceMetadata = fromInstanceMetadata; +exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; +exports.httpRequest = httpRequest; +exports.providerConfigFromInit = providerConfigFromInit; -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); +/***/ }), -// src/timing.ts -var timing = { - setTimeout: (cb, ms) => setTimeout(cb, ms), - clearTimeout: (timeoutId) => clearTimeout(timeoutId) -}; +/***/ 85744: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket == null ? void 0 : socket.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); +"use strict"; + + +var propertyProvider = __nccwpck_require__(42382); +var sharedIniFileLoader = __nccwpck_require__(38924); + +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); + catch (e) { + return functionString; + } +} -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); + } + return config; } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); + } +}; -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - request.setTimeout(timeoutInMs - offset, () => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }); - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = sharedIniFileLoader.getProfileName(init); + const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); + } +}; -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2203); -var MIN_WAIT_TIME = 1e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); + +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +exports.loadConfig = loadConfig; + + +/***/ }), + +/***/ 42382: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); } -__name(writeBody, "writeBody"); -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var _NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { - return instanceOrOptions; +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - var _a, _b, _c; - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; +} + +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; +} + +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = ((_a = sockets[origin]) == null ? void 0 : _a.length) ?? 0; - const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call( - logger, - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; } - } } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") { - return httpAgent; + throw lastProviderError; +}; + +const fromStatic = (staticValue) => () => Promise.resolve(staticValue); + +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") { - return httpsAgent; + try { + resolved = await pending; + hasResult = true; + isConstant = false; } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console + finally { + pending = undefined; + } + return resolved; }; - } - destroy() { - var _a, _b, _c, _d; - (_b = (_a = this.config) == null ? void 0 : _a.httpAgent) == null ? void 0 : _b.destroy(); - (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy(); - } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal == null ? void 0 : abortSignal.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + if (isConstant) { + return resolved; } - } - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}; + +exports.CredentialsProviderError = CredentialsProviderError; +exports.ProviderError = ProviderError; +exports.TokenProviderError = TokenProviderError; +exports.chain = chain; +exports.fromStatic = fromStatic; +exports.memoize = memoize; + + +/***/ }), + +/***/ 39982: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } + else if (Array.isArray(query[key])) { + query[key].push(value); + } + else { + query[key] = [query[key], value]; + } + } + } + return query; +} + +exports.parseQueryString = parseQueryString; + + +/***/ }), + +/***/ 48660: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(70857); +const path_1 = __nccwpck_require__(16928); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; + + +/***/ }), + +/***/ 17669: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(76982); +const path_1 = __nccwpck_require__(16928); +const getHomeDir_1 = __nccwpck_require__(48660); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; + + +/***/ }), + +/***/ 88262: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; +const fs_1 = __nccwpck_require__(79896); +const getSSOTokenFilepath_1 = __nccwpck_require__(17669); +const { readFile } = fs_1.promises; +exports.tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); }; -__name(_NodeHttpHandler, "NodeHttpHandler"); -var NodeHttpHandler = _NodeHttpHandler; +exports.getSSOTokenFromFile = getSSOTokenFromFile; -// src/node-http2-handler.ts +/***/ }), -var import_http22 = __nccwpck_require__(85675); +/***/ 38924: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85675)); +"use strict"; -// src/node-http2-connection-pool.ts -var _NodeHttp2ConnectionPool = class _NodeHttp2ConnectionPool { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); + +var getHomeDir = __nccwpck_require__(48660); +var getSSOTokenFilepath = __nccwpck_require__(17669); +var getSSOTokenFromFile = __nccwpck_require__(88262); +var path = __nccwpck_require__(16928); +var types = __nccwpck_require__(31242); +var slurpFile = __nccwpck_require__(91550); + +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); + return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; +}, { + ...(data.default && { default: data.default }), +}); + +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } } - } } - } + return map; }; -__name(_NodeHttp2ConnectionPool, "NodeHttp2ConnectionPool"); -var NodeHttp2ConnectionPool = _NodeHttp2ConnectionPool; -// src/node-http2-connection-manager.ts -var _NodeHttp2ConnectionManager = class _NodeHttp2ConnectionManager { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); +const swallowError$1 = () => ({}); +const CONFIG_PREFIX_SEPARATOR = "."; +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir.getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = path.join(homeDir, filepath.slice(2)); } - } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2)); } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); + const parsedFiles = await Promise.all([ + slurpFile.slurpFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + slurpFile.slurpFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; +}; + +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => slurpFile.slurpFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); + +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } } - }); } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + return merged; +}; + +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; + +const externalDataInterceptor = { + getFileRecord() { + return slurpFile.fileIntercept; + }, + interceptFile(path, contents) { + slurpFile.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + getSSOTokenFromFile.tokenIntercept[id] = contents; + }, +}; + +Object.defineProperty(exports, "getSSOTokenFromFile", ({ + enumerable: true, + get: function () { return getSSOTokenFromFile.getSSOTokenFromFile; } +})); +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.ENV_PROFILE = ENV_PROFILE; +exports.externalDataInterceptor = externalDataInterceptor; +exports.getProfileName = getProfileName; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.parseKnownFiles = parseKnownFiles; +Object.keys(getHomeDir).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getHomeDir[k]; } + }); +}); +Object.keys(getSSOTokenFilepath).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getSSOTokenFilepath[k]; } + }); +}); + + +/***/ }), + +/***/ 91550: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; + if (!exports.filePromisesHash[path] || options?.ignoreCache) { + exports.filePromisesHash[path] = readFile(path, "utf8"); } - if (!existingConnectionPool.contains(session)) { - return; + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 31242: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - var _a; - const cacheKey = this.getUrlString(requestContext); - (_a = this.sessionCache.get(cacheKey)) == null ? void 0 : _a.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; + + +/***/ }), + +/***/ 38118: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var querystringParser = __nccwpck_require__(39982); + +const parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = querystringParser.parseQueryString(search); + } + return { + hostname, + port: port ? parseInt(port) : undefined, + protocol, + path: pathname, + query, + }; }; -__name(_NodeHttp2ConnectionManager, "NodeHttp2ConnectionManager"); -var NodeHttp2ConnectionManager = _NodeHttp2ConnectionManager; -// src/node-http2-handler.ts -var _NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); +exports.parseUrl = parseUrl; + + +/***/ }), + +/***/ 47809: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(src_exports); + +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(72356); +var import_querystring_builder = __nccwpck_require__(18256); + +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var _FetchHttpHandler = class _FetchHttpHandler { /** * @returns the input if it is an HttpHandler of any class, * or instantiates a new instance of this handler. @@ -86452,191 +77307,149 @@ var _NodeHttp2Handler = class _NodeHttp2Handler { if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { return instanceOrOptions; } - return new _NodeHttp2Handler(instanceOrOptions); + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); + } } destroy() { - this.connectionManager.destroy(); } async handle(request, { abortSignal } = {}) { + var _a; if (!this.config) { this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } } - const { requestTimeout, disableConcurrentStreams } = this.config; - return new Promise((_resolve, _reject) => { - var _a; - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal == null ? void 0 : abortSignal.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: (_a = this.config) == null ? void 0 : _a.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (requestTimeout) { - req.setTimeout(requestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); + const requestTimeoutInMs = this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal == null ? void 0 : abortSignal.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if ((_a = this.config) == null ? void 0 : _a.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); } - }); - writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); - }); + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + config[key] = value; + return config; }); } httpHandlerConfigs() { return this.config ?? {}; } - /** - * Destroys a session. - * @param session The session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } -}; -__name(_NodeHttp2Handler, "NodeHttp2Handler"); -var NodeHttp2Handler = _NodeHttp2Handler; - -// src/stream-collector/collector.ts - -var _Collector = class _Collector extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } }; -__name(_Collector, "Collector"); -var Collector = _Collector; +__name(_FetchHttpHandler, "FetchHttpHandler"); +var FetchHttpHandler = _FetchHttpHandler; -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/stream-collector.ts +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + var _a; + if (typeof Blob === "function" && stream instanceof Blob || ((_a = stream.constructor) == null ? void 0 : _a.name) === "Blob") { + return new Uint8Array(await stream.arrayBuffer()); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); + return collectStream(stream); }, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { +async function collectStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; @@ -86657,7 +77470,7 @@ async function collectReadableStream(stream) { } return collected; } -__name(collectReadableStream, "collectReadableStream"); +__name(collectStream, "collectStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -86666,8 +77479,140 @@ __name(collectReadableStream, "collectReadableStream"); /***/ }), -/***/ 72356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5092: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilBufferFrom = __nccwpck_require__(34677); +var utilUtf8 = __nccwpck_require__(82155); +var buffer = __nccwpck_require__(20181); +var crypto = __nccwpck_require__(76982); + +class Hash { + algorithmIdentifier; + secret; + hash; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret + ? crypto.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) + : crypto.createHash(this.algorithmIdentifier); + } +} +function castSourceData(toCast, encoding) { + if (buffer.Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return utilBufferFrom.fromString(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return utilBufferFrom.fromArrayBuffer(toCast); +} + +exports.Hash = Hash; + + +/***/ }), + +/***/ 68628: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; + + +/***/ }), + +/***/ 34677: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var isArrayBuffer = __nccwpck_require__(68628); +var buffer = __nccwpck_require__(20181); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); +}; + +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; + + +/***/ }), + +/***/ 82155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilBufferFrom = __nccwpck_require__(34677); + +const fromUtf8 = (input) => { + const buf = utilBufferFrom.fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toUint8Array = (data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +exports.fromUtf8 = fromUtf8; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8; + + +/***/ }), + +/***/ 86130: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -86691,297 +77636,1029 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + isArrayBuffer: () => isArrayBuffer }); module.exports = __toCommonJS(src_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - let httpHandler = runtimeConfig.httpHandler; - return { - setHttpHandler(handler) { - httpHandler = handler; - }, - httpHandler() { - return httpHandler; - }, - updateHttpClientConfig(key, value) { - httpHandler.updateHttpClientConfig(key, value); +0 && (0); + + + +/***/ }), + +/***/ 47212: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var protocolHttp = __nccwpck_require__(86382); + +const CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (protocolHttp.HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && + Object.keys(headers) + .map((str) => str.toLowerCase()) + .indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length), + }; + } + catch (error) { + } + } + } + return next({ + ...args, + request, + }); + }; +} +const contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true, +}; +const getContentLengthPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); }, - httpHandlerConfigs() { - return httpHandler.httpHandlerConfigs(); +}); + +exports.contentLengthMiddleware = contentLengthMiddleware; +exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; +exports.getContentLengthPlugin = getContentLengthPlugin; + + +/***/ }), + +/***/ 86382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(12276); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} -// src/Field.ts -var import_types = __nccwpck_require__(90690); -var _Field = class _Field { - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; + + +/***/ }), + +/***/ 12276: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; }; -__name(_Field, "Field"); -var Field = _Field; -// src/Fields.ts -var _Fields = class _Fields { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); }; -__name(_Fields, "Fields"); -var Fields = _Fields; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; + + +/***/ }), + +/***/ 19618: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilRetry = __nccwpck_require__(15518); +var protocolHttp = __nccwpck_require__(64864); +var serviceErrorClassification = __nccwpck_require__(42058); +var uuid = __nccwpck_require__(90266); +var utilMiddleware = __nccwpck_require__(73976); +var smithyClient = __nccwpck_require__(61411); +var isStreamingPayload = __nccwpck_require__(49831); + +const getDefaultRetryQuota = (initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT; + const retryCost = utilRetry.RETRY_COST; + const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); + const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; + const retrieveRetryTokens = (error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); + } + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }; + const releaseRetryTokens = (capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }; + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens, + }); +}; + +const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + +const defaultRetryDecider = (error) => { + if (!error) { + return false; + } + return serviceErrorClassification.isRetryableByTrait(error) || serviceErrorClassification.isClockSkewError(error) || serviceErrorClassification.isThrottlingError(error) || serviceErrorClassification.isTransientError(error); +}; + +const asSdkError = (error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); +}; + +class StandardRetryStrategy { + maxAttemptsProvider; + retryDecider; + delayDecider; + retryQuota; + mode = utilRetry.RETRY_MODES.STANDARD; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS); + } + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } + catch (error) { + maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); + } + while (true) { + try { + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); + } + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } + catch (e) { + const err = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; + } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } + } + } +} +const getDelayFromRetryAfterHeader = (response) => { + if (!protocolHttp.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return retryAfterSeconds * 1000; + const retryAfterDate = new Date(retryAfter); + return retryAfterDate.getTime() - Date.now(); +}; + +class AdaptiveRetryStrategy extends StandardRetryStrategy { + rateLimiter; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter(); + this.mode = utilRetry.RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + }, + }); + } +} + +const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +const CONFIG_MAX_ATTEMPTS = "max_attempts"; +const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + default: utilRetry.DEFAULT_MAX_ATTEMPTS, +}; +const resolveRetryConfig = (input) => { + const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; + const maxAttempts = utilMiddleware.normalizeProvider(_maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS); + return Object.assign(input, { + maxAttempts, + retryStrategy: async () => { + if (retryStrategy) { + return retryStrategy; + } + const retryMode = await utilMiddleware.normalizeProvider(_retryMode)(); + if (retryMode === utilRetry.RETRY_MODES.ADAPTIVE) { + return new utilRetry.AdaptiveRetryStrategy(maxAttempts); + } + return new utilRetry.StandardRetryStrategy(maxAttempts); + }, + }); +}; +const ENV_RETRY_MODE = "AWS_RETRY_MODE"; +const CONFIG_RETRY_MODE = "retry_mode"; +const NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: utilRetry.DEFAULT_RETRY_MODE, +}; + +const omitRetryHeadersMiddleware = () => (next) => async (args) => { + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + delete request.headers[utilRetry.INVOCATION_ID_HEADER]; + delete request.headers[utilRetry.REQUEST_HEADER]; + } + return next(args); +}; +const omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true, +}; +const getOmitRetryHeadersPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + }, +}); + +const retryMiddleware = (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = protocolHttp.HttpRequest.isInstance(request); + if (isRequest) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); + } + while (true) { + try { + if (isRequest) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } + catch (e) { + const retryErrorInfo = getRetryErrorInfo(e); + lastError = asSdkError(e); + if (isRequest && isStreamingPayload.isStreamingPayload(request)) { + (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } + catch (refreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + } + else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) + context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; + return retryStrategy.retry(next, args); + } +}; +const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && + typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && + typeof retryStrategy.recordSuccess !== "undefined"; +const getRetryErrorInfo = (error) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error), + }; + const retryAfterHint = getRetryAfterHint(error.$response); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; +}; +const getRetryErrorType = (error) => { + if (serviceErrorClassification.isThrottlingError(error)) + return "THROTTLING"; + if (serviceErrorClassification.isTransientError(error)) + return "TRANSIENT"; + if (serviceErrorClassification.isServerError(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}; +const retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true, +}; +const getRetryPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + }, +}); +const getRetryAfterHint = (response) => { + if (!protocolHttp.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return new Date(retryAfterSeconds * 1000); + const retryAfterDate = new Date(retryAfter); + return retryAfterDate; +}; + +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; +exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; +exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; +exports.ENV_RETRY_MODE = ENV_RETRY_MODE; +exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS; +exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS; +exports.StandardRetryStrategy = StandardRetryStrategy; +exports.defaultDelayDecider = defaultDelayDecider; +exports.defaultRetryDecider = defaultRetryDecider; +exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; +exports.getRetryAfterHint = getRetryAfterHint; +exports.getRetryPlugin = getRetryPlugin; +exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; +exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; +exports.resolveRetryConfig = resolveRetryConfig; +exports.retryMiddleware = retryMiddleware; +exports.retryMiddlewareOptions = retryMiddlewareOptions; + + +/***/ }), + +/***/ 49831: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; -// src/httpRequest.ts +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isStreamingPayload = void 0; +const stream_1 = __nccwpck_require__(2203); +const isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || + (typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream); +exports.isStreamingPayload = isStreamingPayload; -var _HttpRequest = class _HttpRequest { - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; - } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); - } + +/***/ }), + +/***/ 64864: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(36158); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; }; -__name(_HttpRequest, "HttpRequest"); -var HttpRequest = _HttpRequest; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var _HttpResponse = class _HttpResponse { - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) - return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } }; -__name(_HttpResponse, "HttpResponse"); -var HttpResponse = _HttpResponse; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } } -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; /***/ }), -/***/ 18256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36158: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + + +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(src_exports); -var import_util_uri_escape = __nccwpck_require__(80146); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; -0 && (0); +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), -/***/ 42058: +/***/ 73976: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(36158); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; + + +/***/ }), + +/***/ 9208: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -87004,84 +78681,301 @@ var __copyProps = (to, from, except, desc) => { var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts -var index_exports = {}; -__export(index_exports, { - isBrowserNetworkError: () => isBrowserNetworkError, - isClockSkewCorrectedError: () => isClockSkewCorrectedError, - isClockSkewError: () => isClockSkewError, - isRetryableByTrait: () => isRetryableByTrait, - isServerError: () => isServerError, - isThrottlingError: () => isThrottlingError, - isTransientError: () => isTransientError +var src_exports = {}; +__export(src_exports, { + constructStack: () => constructStack }); -module.exports = __toCommonJS(index_exports); - -// src/constants.ts -var CLOCK_SKEW_ERROR_CODES = [ - "AuthFailure", - "InvalidSignatureException", - "RequestExpired", - "RequestInTheFuture", - "RequestTimeTooSkewed", - "SignatureDoesNotMatch" -]; -var THROTTLING_ERROR_CODES = [ - "BandwidthLimitExceeded", - "EC2ThrottledException", - "LimitExceededException", - "PriorRequestNotComplete", - "ProvisionedThroughputExceededException", - "RequestLimitExceeded", - "RequestThrottled", - "RequestThrottledException", - "SlowDown", - "ThrottledException", - "Throttling", - "ThrottlingException", - "TooManyRequestsException", - "TransactionInProgressException" - // DynamoDB -]; -var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; -var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; -var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; +module.exports = __toCommonJS(src_exports); -// src/index.ts -var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); -var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); -var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); -var isBrowserNetworkError = /* @__PURE__ */ __name((error) => { - const errorMessages = /* @__PURE__ */ new Set([ - "Failed to fetch", - // Chrome - "NetworkError when attempting to fetch resource", - // Firefox - "The Internet connection appears to be offline", - // Safari 16 - "Load failed", - // Safari 17+ - "Network request failed" - // `cross-fetch` - ]); - const isValid = error && error instanceof TypeError; - if (!isValid) { - return false; +// src/MiddlewareStack.ts +var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); } - return errorMessages.has(error.message); -}, "isBrowserNetworkError"); -var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); -var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); -var isServerError = /* @__PURE__ */ __name((error) => { - if (error.$metadata?.httpStatusCode !== void 0) { - const statusCode = error.$metadata.httpStatusCode; - if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { - return true; + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); } - return false; } - return false; -}, "isServerError"); + return _aliases; +}, "getAllAliases"); +var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}, "getMiddlewareNameWithAliases"); +var constructStack = /* @__PURE__ */ __name(() => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = /* @__PURE__ */ __name((entries) => entries.sort( + (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] + ), "sort"); + const removeByName = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByName"); + const removeByReference = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByReference"); + const cloneTo = /* @__PURE__ */ __name((toStack) => { + var _a; + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + (_a = toStack.identifyOnResolve) == null ? void 0 : _a.call(toStack, stack.identifyOnResolve()); + return toStack; + }, "cloneTo"); + const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }, "expandRelativeMiddlewareList"); + const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === void 0) { + if (debug) { + return; + } + throw new Error( + `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` + ); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce( + (wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, + [] + ); + return mainChain; + }, "getMiddlewareList"); + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex( + (entry2) => { + var _a; + return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); + } + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` + ); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex( + (entry2) => { + var _a; + return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); + } + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` + ); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + var _a; + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve( + identifyOnResolve || cloned.identifyOnResolve() || (((_a = from.identifyOnResolve) == null ? void 0 : _a.call(from)) ?? false) + ); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? mw.relation + " " + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + } + }; + return stack; +}, "constructStack"); +var stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 +}; +var priorityWeights = { + high: 3, + normal: 2, + low: 1 +}; // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -87090,12 +78984,14 @@ var isServerError = /* @__PURE__ */ __name((error) => { /***/ }), -/***/ 75118: +/***/ 61279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -87110,661 +79006,776 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts -var index_exports = {}; -__export(index_exports, { - ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER, - ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A, - ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM, - ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS, - AMZ_DATE_HEADER: () => AMZ_DATE_HEADER, - AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM, - AUTH_HEADER: () => AUTH_HEADER, - CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM, - DATE_HEADER: () => DATE_HEADER, - EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER, - EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM, - GENERATED_HEADERS: () => GENERATED_HEADERS, - HOST_HEADER: () => HOST_HEADER, - KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER, - MAX_CACHE_SIZE: () => MAX_CACHE_SIZE, - MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL, - PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN, - REGION_SET_PARAM: () => REGION_SET_PARAM, - SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN, - SHA256_HEADER: () => SHA256_HEADER, - SIGNATURE_HEADER: () => SIGNATURE_HEADER, - SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM, - SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM, - SignatureV4: () => SignatureV4, - SignatureV4Base: () => SignatureV4Base, - TOKEN_HEADER: () => TOKEN_HEADER, - TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM, - UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS, - UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD, - clearCredentialCache: () => clearCredentialCache, - createScope: () => createScope, - getCanonicalHeaders: () => getCanonicalHeaders, - getCanonicalQuery: () => getCanonicalQuery, - getPayloadHash: () => getPayloadHash, - getSigningKey: () => getSigningKey, - hasHeader: () => hasHeader, - moveHeadersToQuery: () => moveHeadersToQuery, - prepareRequest: () => prepareRequest, - signatureV4aContainer: () => signatureV4aContainer +var src_exports = {}; +__export(src_exports, { + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector }); -module.exports = __toCommonJS(index_exports); - -// src/SignatureV4.ts +module.exports = __toCommonJS(src_exports); -var import_util_utf85 = __nccwpck_require__(67529); +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(72356); +var import_querystring_builder = __nccwpck_require__(18256); +var import_http = __nccwpck_require__(58611); +var import_https = __nccwpck_require__(65692); // src/constants.ts -var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; -var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; -var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; -var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; -var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; -var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; -var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; -var REGION_SET_PARAM = "X-Amz-Region-Set"; -var AUTH_HEADER = "authorization"; -var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); -var DATE_HEADER = "date"; -var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; -var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); -var SHA256_HEADER = "x-amz-content-sha256"; -var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); -var HOST_HEADER = "host"; -var ALWAYS_UNSIGNABLE_HEADERS = { - authorization: true, - "cache-control": true, - connection: true, - expect: true, - from: true, - "keep-alive": true, - "max-forwards": true, - pragma: true, - referer: true, - te: true, - trailer: true, - "transfer-encoding": true, - upgrade: true, - "user-agent": true, - "x-amzn-trace-id": true -}; -var PROXY_HEADER_PATTERN = /^proxy-/; -var SEC_HEADER_PATTERN = /^sec-/; -var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; -var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; -var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; -var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; -var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -var MAX_CACHE_SIZE = 50; -var KEY_TYPE_IDENTIFIER = "aws4_request"; -var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; - -// src/credentialDerivation.ts -var import_util_hex_encoding = __nccwpck_require__(7299); -var import_util_utf8 = __nccwpck_require__(67529); -var signingKeyCache = {}; -var cacheQueue = []; -var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); -var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac(sha256Constructor, key, signable); - } - return signingKeyCache[cacheKey] = key; -}, "getSigningKey"); -var clearCredentialCache = /* @__PURE__ */ __name(() => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; - }); -}, "clearCredentialCache"); -var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { - const hash = new ctor(secret); - hash.update((0, import_util_utf8.toUint8Array)(data)); - return hash.digest(); -}, "hmac"); - -// src/getCanonicalHeaders.ts -var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == void 0) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { - continue; - } - } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } - return canonical; -}, "getCanonicalHeaders"); + return transformedHeaders; +}, "getTransformedHeaders"); -// src/getPayloadHash.ts -var import_is_array_buffer = __nccwpck_require__(52706); +// src/timing.ts +var timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId) +}; -var import_util_utf82 = __nccwpck_require__(67529); -var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; } - if (body == void 0) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update((0, import_util_utf82.toUint8Array)(body)); - return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket == null ? void 0 : socket.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; } - return UNSIGNED_PAYLOAD; -}, "getPayloadHash"); - -// src/HeaderFormatter.ts + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); -var import_util_utf83 = __nccwpck_require__(67529); -var HeaderFormatter = class { - static { - __name(this, "HeaderFormatter"); +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = (0, import_util_utf83.fromUtf8)(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); } - return out; + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8 /* timestamp */; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } -}; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -var Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + request.setTimeout(timeoutInMs - offset, () => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }); + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; } - static { - __name(this, "Int64"); + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2203); +var MIN_WAIT_TIME = 1e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; } - if (number < 0) { - negate(bytes); + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; } - return new _Int64(bytes); + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var _NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); } /** - * Called implicitly by infix arithmetic operators. + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); + static create(instanceOrOptions) { + if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { + return instanceOrOptions; } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + return new _NodeHttpHandler(instanceOrOptions); } - toString() { - return String(this.valueOf()); + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + var _a, _b, _c; + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = ((_a = sockets[origin]) == null ? void 0 : _a.length) ?? 0; + const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call( + logger, + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; } -}; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) break; + destroy() { + var _a, _b, _c, _d; + (_b = (_a = this.config) == null ? void 0 : _a.httpAgent) == null ? void 0 : _b.destroy(); + (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy(); } -} -__name(negate, "negate"); - -// src/headerUtil.ts -var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal == null ? void 0 : abortSignal.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); } - return false; -}, "hasHeader"); - -// src/moveHeadersToQuery.ts -var import_protocol_http = __nccwpck_require__(74996); -var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { - const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { - query[name] = headers[name]; - delete headers[name]; - } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); } - return { - ...request, - headers, - query - }; -}, "moveHeadersToQuery"); - -// src/prepareRequest.ts - -var prepareRequest = /* @__PURE__ */ __name((request) => { - request = import_protocol_http.HttpRequest.clone(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } + httpHandlerConfigs() { + return this.config ?? {}; } - return request; -}, "prepareRequest"); +}; +__name(_NodeHttpHandler, "NodeHttpHandler"); +var NodeHttpHandler = _NodeHttpHandler; + +// src/node-http2-handler.ts -// src/SignatureV4Base.ts -var import_util_middleware = __nccwpck_require__(83732); +var import_http22 = __nccwpck_require__(85675); -var import_util_utf84 = __nccwpck_require__(67529); +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85675)); -// src/getCanonicalQuery.ts -var import_util_uri_escape = __nccwpck_require__(87938); -var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query)) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; +// src/node-http2-connection-pool.ts +var _NodeHttp2ConnectionPool = class _NodeHttp2ConnectionPool { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); } - const encodedKey = (0, import_util_uri_escape.escapeUri)(key); - keys.push(encodedKey); - const value = query[key]; - if (typeof value === "string") { - serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; - } else if (Array.isArray(value)) { - serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } } } - return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); -}, "getCanonicalQuery"); +}; +__name(_NodeHttp2ConnectionPool, "NodeHttp2ConnectionPool"); +var NodeHttp2ConnectionPool = _NodeHttp2ConnectionPool; -// src/utilDate.ts -var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); -var toDate = /* @__PURE__ */ __name((time) => { - if (typeof time === "number") { - return new Date(time * 1e3); +// src/node-http2-connection-manager.ts +var _NodeHttp2ConnectionManager = class _NodeHttp2ConnectionManager { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); + } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - if (typeof time === "string") { - if (Number(time)) { - return new Date(Number(time) * 1e3); + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; } - return new Date(time); - } - return time; -}, "toDate"); - -// src/SignatureV4Base.ts -var SignatureV4Base = class { - static { - __name(this, "SignatureV4Base"); + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); } - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - this.service = service; - this.sha256 = sha256; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); - this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); - } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} - -${sortedHeaders.join(";")} -${payloadHash}`; + release(requestContext, session) { + var _a; + const cacheKey = this.getUrlString(requestContext); + (_a = this.sessionCache.get(cacheKey)) == null ? void 0 : _a.offerLast(session); } - async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { - const hash = new this.sha256(); - hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); - const hashedRequest = await hash.digest(); - return `${algorithmIdentifier} -${longDate} -${credentialScope} -${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; - } - getCanonicalPath({ path }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path.split("/")) { - if (pathSegment?.length === 0) continue; - if (pathSegment === ".") continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } else { - normalizedPathSegments.push(pathSegment); + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); } + connectionPool.remove(session); } - const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; - const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); + this.sessionCache.delete(key); } - return path; } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) - typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) - typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); } + this.config.maxConcurrency = maxConcurrentStreams; } - formatDate(now) { - const longDate = iso8601(now).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8) - }; + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; } - getCanonicalHeaderList(headers) { - return Object.keys(headers).sort().join(";"); + getUrlString(request) { + return request.destination.toString(); } }; +__name(_NodeHttp2ConnectionManager, "NodeHttp2ConnectionManager"); +var NodeHttp2ConnectionManager = _NodeHttp2ConnectionManager; -// src/SignatureV4.ts -var SignatureV4 = class extends SignatureV4Base { - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - super({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath +// src/node-http2-handler.ts +var _NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } }); - this.headerFormatter = new HeaderFormatter(); - } - static { - __name(this, "SignatureV4"); } - async presign(originalRequest, options = {}) { - const { - signingDate = /* @__PURE__ */ new Date(), - expiresIn = 3600, - unsignableHeaders, - unhoistableHeaders, - signableHeaders, - hoistableHeaders, - signingRegion, - signingService - } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { longDate, shortDate } = this.formatDate(signingDate); - if (expiresIn > MAX_PRESIGNED_TTL) { - return Promise.reject( - "Signature version 4 presigned URLs must have an expiration date less than one week in the future" - ); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { + return instanceOrOptions; } - const scope = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) - ); - return request; + return new _NodeHttp2Handler(instanceOrOptions); } - async sign(toSign, options) { - if (typeof toSign === "string") { - return this.signString(toSign, options); - } else if (toSign.headers && toSign.payload) { - return this.signEvent(toSign, options); - } else if (toSign.message) { - return this.signMessage(toSign, options); - } else { - return this.signRequest(toSign, options); - } - } - async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? await this.regionProvider(); - const { shortDate, longDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); - const hash = new this.sha256(); - hash.update(headers); - const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); - } - async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { - const promise = this.signEvent( - { - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body - }, - { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } - ); - return promise.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { shortDate } = this.formatDate(signingDate); - const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - async signRequest(requestToSign, { - signingDate = /* @__PURE__ */ new Date(), - signableHeaders, - unsignableHeaders, - signingRegion, - signingService - } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; - } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, payloadHash) - ); - request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; - return request; + } + const { requestTimeout, disableConcurrentStreams } = this.config; + return new Promise((_resolve, _reject) => { + var _a; + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal == null ? void 0 : abortSignal.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: (_a = this.config) == null ? void 0 : _a.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (requestTimeout) { + req.setTimeout(requestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); + }); } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign( - longDate, - credentialScope, - canonicalRequest, - ALGORITHM_IDENTIFIER - ); - const hash = new this.sha256(await keyPromise); - hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session The session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } } }; +__name(_NodeHttp2Handler, "NodeHttp2Handler"); +var NodeHttp2Handler = _NodeHttp2Handler; -// src/signature-v4a-container.ts -var signatureV4aContainer = { - SignatureV4a: null -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 52706: -/***/ ((module) => { +// src/stream-collector/collector.ts -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var _Collector = class _Collector extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +__name(_Collector, "Collector"); +var Collector = _Collector; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(index_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -87773,7 +79784,7 @@ var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "func /***/ }), -/***/ 74996: +/***/ 72356: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -87796,8 +79807,8 @@ var __copyProps = (to, from, except, desc) => { var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts -var index_exports = {}; -__export(index_exports, { +var src_exports = {}; +__export(src_exports, { Field: () => Field, Fields: () => Fields, HttpRequest: () => HttpRequest, @@ -87807,22 +79818,23 @@ __export(index_exports, { isValidHostname: () => isValidHostname, resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig }); -module.exports = __toCommonJS(index_exports); +module.exports = __toCommonJS(src_exports); // src/extensions/httpExtensionConfiguration.ts var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + let httpHandler = runtimeConfig.httpHandler; return { setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; + httpHandler = handler; }, httpHandler() { - return runtimeConfig.httpHandler; + return httpHandler; }, updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + httpHandler.updateHttpClientConfig(key, value); }, httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); + return httpHandler.httpHandlerConfigs(); } }; }, "getHttpHandlerExtensionConfiguration"); @@ -87833,11 +79845,8 @@ var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensi }, "resolveHttpHandlerRuntimeConfig"); // src/Field.ts -var import_types = __nccwpck_require__(59442); -var Field = class { - static { - __name(this, "Field"); - } +var import_types = __nccwpck_require__(90690); +var _Field = class _Field { constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { this.name = name; this.kind = kind; @@ -87884,17 +79893,16 @@ var Field = class { return this.values; } }; +__name(_Field, "Field"); +var Field = _Field; // src/Fields.ts -var Fields = class { +var _Fields = class _Fields { constructor({ fields = [], encoding = "utf-8" }) { this.entries = {}; fields.forEach(this.setField.bind(this)); this.encoding = encoding; } - static { - __name(this, "Fields"); - } /** * Set entry for a {@link Field} name. The `name` * attribute will be used to key the collection. @@ -87934,13 +79942,12 @@ var Fields = class { return Object.values(this.entries).filter((field) => field.kind === kind); } }; +__name(_Fields, "Fields"); +var Fields = _Fields; // src/httpRequest.ts -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } +var _HttpRequest = class _HttpRequest { constructor(options) { this.method = options.method || "GET"; this.hostname = options.hostname || "localhost"; @@ -87990,6 +79997,8 @@ var HttpRequest = class _HttpRequest { return _HttpRequest.clone(this); } }; +__name(_HttpRequest, "HttpRequest"); +var HttpRequest = _HttpRequest; function cloneQuery(query) { return Object.keys(query).reduce((carry, paramName) => { const param = query[paramName]; @@ -88001,170 +80010,30 @@ function cloneQuery(query) { } __name(cloneQuery, "cloneQuery"); -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } -}; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 59442: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +// src/httpResponse.ts +var _HttpResponse = class _HttpResponse { + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +}; +__name(_HttpResponse, "HttpResponse"); +var HttpResponse = _HttpResponse; -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -88173,7 +80042,7 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 91207: +/***/ 18256: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -88196,26 +80065,32 @@ var __copyProps = (to, from, except, desc) => { var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts -var index_exports = {}; -__export(index_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString +var src_exports = {}; +__export(src_exports, { + buildQueryString: () => buildQueryString }); -module.exports = __toCommonJS(index_exports); -var import_is_array_buffer = __nccwpck_require__(52706); -var import_buffer = __nccwpck_require__(20181); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); +module.exports = __toCommonJS(src_exports); +var import_util_uri_escape = __nccwpck_require__(80146); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); + } } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -88224,236 +80099,1095 @@ var fromString = /* @__PURE__ */ __name((input, encoding) => { /***/ }), -/***/ 7299: -/***/ ((module) => { +/***/ 42058: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + + +const CLOCK_SKEW_ERROR_CODES = [ + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch", +]; +const THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException", +]; +const TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; +const NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; + +const isRetryableByTrait = (error) => error?.$retryable !== undefined; +const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name); +const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; +const isBrowserNetworkError = (error) => { + const errorMessages = new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed", + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; + } + return errorMessages.has(error.message); +}; +const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || + THROTTLING_ERROR_CODES.includes(error.name) || + error.$retryable?.throttling == true; +const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || + isClockSkewCorrectedError(error) || + TRANSIENT_ERROR_CODES.includes(error.name) || + NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || + NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || + TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || + isBrowserNetworkError(error) || + (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1)); +const isServerError = (error) => { + if (error.$metadata?.httpStatusCode !== undefined) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; + } + return false; + } + return false; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; + +exports.isBrowserNetworkError = isBrowserNetworkError; +exports.isClockSkewCorrectedError = isClockSkewCorrectedError; +exports.isClockSkewError = isClockSkewError; +exports.isRetryableByTrait = isRetryableByTrait; +exports.isServerError = isServerError; +exports.isThrottlingError = isThrottlingError; +exports.isTransientError = isTransientError; + + +/***/ }), + +/***/ 75118: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilHexEncoding = __nccwpck_require__(7299); +var utilUtf8 = __nccwpck_require__(67529); +var isArrayBuffer = __nccwpck_require__(52706); +var protocolHttp = __nccwpck_require__(74996); +var utilMiddleware = __nccwpck_require__(83732); +var utilUriEscape = __nccwpck_require__(87938); + +const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +const AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +const EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +const SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +const TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +const REGION_SET_PARAM = "X-Amz-Region-Set"; +const AUTH_HEADER = "authorization"; +const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +const DATE_HEADER = "date"; +const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +const SHA256_HEADER = "x-amz-content-sha256"; +const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +const HOST_HEADER = "host"; +const ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true, +}; +const PROXY_HEADER_PATTERN = /^proxy-/; +const SEC_HEADER_PATTERN = /^sec-/; +const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; +const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; +const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +const MAX_CACHE_SIZE = 50; +const KEY_TYPE_IDENTIFIER = "aws4_request"; +const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +const signingKeyCache = {}; +const cacheQueue = []; +const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; +const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return (signingKeyCache[cacheKey] = key); +}; +const clearCredentialCache = () => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}; +const hmac = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(utilUtf8.toUint8Array(data)); + return hash.digest(); +}; + +const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == undefined) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || + unsignableHeaders?.has(canonicalHeaderName) || + PROXY_HEADER_PATTERN.test(canonicalHeaderName) || + SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(index_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; +const getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == undefined) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } + else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer.isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(utilUtf8.toUint8Array(body)); + return utilHexEncoding.toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}; + +class HeaderFormatter { + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = utilUtf8.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = utilUtf8.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } } -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); } - } - return out; } -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } } -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +const hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}; + +const moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = protocolHttp.HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if ((lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) || + options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query, + }; +}; + +const prepareRequest = (request) => { + request = protocolHttp.HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}; + +const getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = utilUriEscape.escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`; + } + else if (Array.isArray(value)) { + serialized[encodedKey] = value + .slice(0) + .reduce((encoded, value) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value)}`]), []) + .sort() + .join("&"); + } + } + return keys + .sort() + .map((key) => serialized[key]) + .filter((serialized) => serialized) + .join("&"); +}; + +const iso8601 = (time) => toDate(time) + .toISOString() + .replace(/\.\d{3}Z$/, "Z"); +const toDate = (time) => { + if (typeof time === "number") { + return new Date(time * 1000); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1000); + } + return new Date(time); + } + return time; +}; + +class SignatureV4Base { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = utilMiddleware.normalizeProvider(region); + this.credentialProvider = utilMiddleware.normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update(utilUtf8.toUint8Array(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${utilHexEncoding.toHex(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } + else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = utilUriEscape.escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || + typeof credentials.accessKeyId !== "string" || + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now) { + const longDate = iso8601(now).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8), + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } +} +class SignatureV4 extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath, + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } + else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } + else if (toSign.message) { + return this.signMessage(toSign, options); + } + else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = utilHexEncoding.toHex(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload, + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); + } + async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) { + const promise = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body, + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature, + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = + `${ALGORITHM_IDENTIFIER} ` + + `Credential=${credentials.accessKeyId}/${scope}, ` + + `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + + `Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash = new this.sha256(await keyPromise); + hash.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } +} + +const signatureV4aContainer = { + SignatureV4a: null, +}; + +exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; +exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; +exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; +exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; +exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; +exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; +exports.AUTH_HEADER = AUTH_HEADER; +exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; +exports.DATE_HEADER = DATE_HEADER; +exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; +exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; +exports.GENERATED_HEADERS = GENERATED_HEADERS; +exports.HOST_HEADER = HOST_HEADER; +exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; +exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; +exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; +exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; +exports.REGION_SET_PARAM = REGION_SET_PARAM; +exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; +exports.SHA256_HEADER = SHA256_HEADER; +exports.SIGNATURE_HEADER = SIGNATURE_HEADER; +exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; +exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; +exports.SignatureV4 = SignatureV4; +exports.SignatureV4Base = SignatureV4Base; +exports.TOKEN_HEADER = TOKEN_HEADER; +exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; +exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; +exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; +exports.clearCredentialCache = clearCredentialCache; +exports.createScope = createScope; +exports.getCanonicalHeaders = getCanonicalHeaders; +exports.getCanonicalQuery = getCanonicalQuery; +exports.getPayloadHash = getPayloadHash; +exports.getSigningKey = getSigningKey; +exports.hasHeader = hasHeader; +exports.moveHeadersToQuery = moveHeadersToQuery; +exports.prepareRequest = prepareRequest; +exports.signatureV4aContainer = signatureV4aContainer; /***/ }), -/***/ 83732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 52706: +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +exports.isArrayBuffer = isArrayBuffer; + + +/***/ }), + +/***/ 74996: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(59442); + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + }, + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(index_exports); +class Field { + name; + kind; + values; + constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(59442); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: +exports.Field = Field; +exports.Fields = Fields; +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.isValidHostname = isValidHostname; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; -0 && (0); +/***/ }), +/***/ 59442: +/***/ ((__unused_webpack_module, exports) => { -/***/ }), +"use strict"; -/***/ 87938: -/***/ ((module) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(index_exports); +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: +const SMITHY_CONTEXT_KEY = "__smithy_context"; -0 && (0); +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), -/***/ 67529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 91207: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +"use strict"; + + +var isArrayBuffer = __nccwpck_require__(52706); +var buffer = __nccwpck_require__(20181); + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer.Buffer.from(input, offset, length); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(index_exports); +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromString = fromString; -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(91207); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); +/***/ }), -// src/toUtf8.ts +/***/ 7299: +/***/ ((__unused_webpack_module, exports) => { -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: +"use strict"; -0 && (0); +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +exports.fromHex = fromHex; +exports.toHex = toHex; + + +/***/ }), + +/***/ 83732: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var types = __nccwpck_require__(59442); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; + + +/***/ }), + +/***/ 87938: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; + + +/***/ }), + +/***/ 67529: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var utilBufferFrom = __nccwpck_require__(91207); + +const fromUtf8 = (input) => { + const buf = utilBufferFrom.fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toUint8Array = (data) => { + if (typeof data === "string") { + return fromUtf8(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +exports.fromUtf8 = fromUtf8; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8; /***/ }), @@ -89918,59 +82652,41 @@ exports.toBase64 = toBase64; /***/ }), /***/ 13638: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(index_exports); -// src/calculateBodyLength.ts -var import_fs = __nccwpck_require__(79896); -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (!body) { - return 0; - } - if (typeof body === "string") { - return Buffer.byteLength(body); - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; - } else if (typeof body.start === "number" && typeof body.end === "number") { - return body.end + 1 - body.start; - } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) { - return (0, import_fs.lstatSync)(body.path).size; - } else if (typeof body.fd === "number") { - return (0, import_fs.fstatSync)(body.fd).size; - } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: +var node_fs = __nccwpck_require__(73024); -0 && (0); +const calculateBodyLength = (body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } + else if (body instanceof node_fs.ReadStream) { + if (body.path != null) { + return node_fs.lstatSync(body.path).size; + } + else if (typeof body.fd === "number") { + return node_fs.fstatSync(body.fd).size; + } + } + throw new Error(`Body Length computation failed for ${body}`); +}; +exports.calculateBodyLength = calculateBodyLength; /***/ }), @@ -90027,472 +82743,316 @@ var fromString = /* @__PURE__ */ __name((input, encoding) => { /***/ }), /***/ 56716: -/***/ ((module) => { +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - SelectorType: () => SelectorType, - booleanSelector: () => booleanSelector, - numberSelector: () => numberSelector -}); -module.exports = __toCommonJS(index_exports); -// src/booleanSelector.ts -var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) return void 0; - if (obj[key] === "true") return true; - if (obj[key] === "false") return false; - throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); -}, "booleanSelector"); - -// src/numberSelector.ts -var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) return void 0; - const numberValue = parseInt(obj[key], 10); - if (Number.isNaN(numberValue)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); - } - return numberValue; -}, "numberSelector"); - -// src/types.ts -var SelectorType = /* @__PURE__ */ ((SelectorType2) => { - SelectorType2["ENV"] = "env"; - SelectorType2["CONFIG"] = "shared config entry"; - return SelectorType2; -})(SelectorType || {}); -// Annotate the CommonJS export names for ESM import in node: +const booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}; -0 && (0); +const numberSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}; +exports.SelectorType = void 0; +(function (SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; +})(exports.SelectorType || (exports.SelectorType = {})); + +exports.booleanSelector = booleanSelector; +exports.numberSelector = numberSelector; /***/ }), /***/ 15435: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - resolveDefaultsModeConfig: () => resolveDefaultsModeConfig -}); -module.exports = __toCommonJS(index_exports); -// src/resolveDefaultsModeConfig.ts -var import_config_resolver = __nccwpck_require__(39316); -var import_node_config_provider = __nccwpck_require__(78257); -var import_property_provider = __nccwpck_require__(94377); +var configResolver = __nccwpck_require__(39316); +var nodeConfigProvider = __nccwpck_require__(78257); +var propertyProvider = __nccwpck_require__(94377); -// src/constants.ts -var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; -var AWS_REGION_ENV = "AWS_REGION"; -var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; -var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; - -// src/defaultsModeConfig.ts -var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; -var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; -var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => { - return env[AWS_DEFAULTS_MODE_ENV]; - }, "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => { - return profile[AWS_DEFAULTS_MODE_CONFIG]; - }, "configFileSelector"), - default: "legacy" -}; - -// src/resolveDefaultsModeConfig.ts -var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ - region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), - defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) -} = {}) => (0, import_property_provider.memoize)(async () => { - const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; - switch (mode?.toLowerCase()) { - case "auto": - return resolveNodeDefaultsModeAuto(region); - case "in-region": - case "cross-region": - case "mobile": - case "standard": - case "legacy": - return Promise.resolve(mode?.toLocaleLowerCase()); - case void 0: - return Promise.resolve("legacy"); - default: - throw new Error( - `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` - ); - } -}), "resolveDefaultsModeConfig"); -var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => { - if (clientRegion) { - const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; - const inferredRegion = await inferPhysicalRegion(); - if (!inferredRegion) { - return "standard"; +const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +const AWS_REGION_ENV = "AWS_REGION"; +const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +const IMDS_REGION_PATH = "/latest/meta-data/placement/region"; + +const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy", +}; + +const resolveDefaultsModeConfig = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => propertyProvider.memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case undefined: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); } - if (resolvedRegion === inferredRegion) { - return "in-region"; - } else { - return "cross-region"; +}); +const resolveNodeDefaultsModeAuto = async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } + else { + return "cross-region"; + } } - } - return "standard"; -}, "resolveNodeDefaultsModeAuto"); -var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { - if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { - return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; - } - if (!process.env[ENV_IMDS_DISABLED]) { - try { - const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(40566))); - const endpoint = await getInstanceMetadataEndpoint(); - return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); - } catch (e) { + return "standard"; +}; +const inferPhysicalRegion = async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; } - } -}, "inferPhysicalRegion"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); + if (!process.env[ENV_IMDS_DISABLED]) { + try { + const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve(/* import() */).then(__nccwpck_require__.t.bind(__nccwpck_require__, 40566, 19)); + const endpoint = await getInstanceMetadataEndpoint(); + return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); + } + catch (e) { + } + } +}; +exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; /***/ }), /***/ 78257: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(index_exports); +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/configLoader.ts +"use strict"; -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(94377); +var propertyProvider = __nccwpck_require__(94377); +var sharedIniFileLoader = __nccwpck_require__(59645); -// src/getSelectorName.ts function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } + catch (e) { + return functionString; + } } -__name(getSelectorName, "getSelectorName"); -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); + } + return config; } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); - } -}, "fromEnv"); - -// src/fromSharedConfigFiles.ts - -var import_shared_ini_file_loader = __nccwpck_require__(59645); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); - -// src/fromStatic.ts - -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +}; -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = sharedIniFileLoader.getProfileName(init); + const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } + catch (e) { + throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); + } +}; -0 && (0); +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +exports.loadConfig = loadConfig; /***/ }), /***/ 94377: -/***/ ((module) => { +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize -}); -module.exports = __toCommonJS(index_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -}; + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +} -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); - } -}; +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); + } +} -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - static { - __name(this, "TokenProviderError"); - } -}; +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); + } +} -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - } - throw lastProviderError; -}, "chain"); + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +const fromStatic = (staticValue) => () => Promise.resolve(staticValue); -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +}; +exports.CredentialsProviderError = CredentialsProviderError; +exports.ProviderError = ProviderError; +exports.TokenProviderError = TokenProviderError; +exports.chain = chain; +exports.fromStatic = fromStatic; +exports.memoize = memoize; /***/ }), @@ -90576,1073 +83136,892 @@ exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), /***/ 59645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - SSOToken: () => import_getSSOTokenFromFile2.SSOToken, - externalDataInterceptor: () => externalDataInterceptor, - getProfileName: () => getProfileName, - getSSOTokenFromFile: () => import_getSSOTokenFromFile2.getSSOTokenFromFile, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(45819), module.exports); +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); +"use strict"; -// src/index.ts -__reExport(index_exports, __nccwpck_require__(2824), module.exports); -var import_getSSOTokenFromFile2 = __nccwpck_require__(60127); -// src/loadSharedConfigFiles.ts +var getHomeDir = __nccwpck_require__(45819); +var getSSOTokenFilepath = __nccwpck_require__(2824); +var getSSOTokenFromFile = __nccwpck_require__(60127); +var path = __nccwpck_require__(16928); +var types = __nccwpck_require__(79969); +var slurpFile = __nccwpck_require__(45103); +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; -// src/getConfigData.ts -var import_types = __nccwpck_require__(79969); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + if (indexOfSeparator === -1) { + return false; + } + return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; acc[updatedKey] = value; return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } - } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(16928); -var import_getHomeDir = __nccwpck_require__(45819); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(45819); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(45819); - -// src/parseIni.ts +}, { + ...(data.default && { default: data.default }), +}); -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } } - } - } - } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(45103); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); - -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(45103); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); - -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } } - } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); - -// src/externalDataInterceptor.ts -var import_getSSOTokenFromFile = __nccwpck_require__(60127); -var import_slurpFile3 = __nccwpck_require__(45103); -var externalDataInterceptor = { - getFileRecord() { - return import_slurpFile3.fileIntercept; - }, - interceptFile(path, contents) { - import_slurpFile3.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return import_getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - import_getSSOTokenFromFile.tokenIntercept[id] = contents; - } + return map; }; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 45103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; -const fs_1 = __nccwpck_require__(79896); -const { readFile } = fs_1.promises; -exports.filePromisesHash = {}; -exports.fileIntercept = {}; -const slurpFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; +const swallowError$1 = () => ({}); +const CONFIG_PREFIX_SEPARATOR = "."; +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir.getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = path.join(homeDir, filepath.slice(2)); } - if (!exports.filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - exports.filePromisesHash[path] = readFile(path, "utf8"); + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2)); } - return exports.filePromisesHash[path]; + const parsedFiles = await Promise.all([ + slurpFile.slurpFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + slurpFile.slurpFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; }; -exports.slurpFile = slurpFile; +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); -/***/ }), - -/***/ 79969: -/***/ ((module) => { +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => slurpFile.slurpFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } + } + } + return merged; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +const externalDataInterceptor = { + getFileRecord() { + return slurpFile.fileIntercept; + }, + interceptFile(path, contents) { + slurpFile.fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + getSSOTokenFromFile.tokenIntercept[id] = contents; + }, +}; -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") +Object.defineProperty(exports, "getSSOTokenFromFile", ({ + enumerable: true, + get: function () { return getSSOTokenFromFile.getSSOTokenFromFile; } +})); +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.ENV_PROFILE = ENV_PROFILE; +exports.externalDataInterceptor = externalDataInterceptor; +exports.getProfileName = getProfileName; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.parseKnownFiles = parseKnownFiles; +Object.keys(getHomeDir).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getHomeDir[k]; } }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") +}); +Object.keys(getSSOTokenFilepath).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return getSSOTokenFilepath[k]; } }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +}); + + +/***/ }), + +/***/ 45103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = exports.fileIntercept = exports.filePromisesHash = void 0; +const fs_1 = __nccwpck_require__(79896); +const { readFile } = fs_1.promises; +exports.filePromisesHash = {}; +exports.fileIntercept = {}; +const slurpFile = (path, options) => { + if (exports.fileIntercept[path] !== undefined) { + return exports.fileIntercept[path]; } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); + if (!exports.filePromisesHash[path] || options?.ignoreCache) { + exports.filePromisesHash[path] = readFile(path, "utf8"); + } + return exports.filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); +/***/ }), -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; +/***/ 79969: +/***/ ((__unused_webpack_module, exports) => { -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +"use strict"; -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), /***/ 79674: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - EndpointCache: () => EndpointCache, - EndpointError: () => EndpointError, - customEndpointFunctions: () => customEndpointFunctions, - isIpAddress: () => isIpAddress, - isValidHostLabel: () => isValidHostLabel, - resolveEndpoint: () => resolveEndpoint -}); -module.exports = __toCommonJS(index_exports); -// src/cache/EndpointCache.ts -var EndpointCache = class { - /** - * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed - * before keys are dropped. - * @param [params] - list of params to consider as part of the cache key. - * - * If the params list is not populated, no caching will happen. - * This may be out of order depending on how the object is created and arrives to this class. - */ - constructor({ size, params }) { - this.data = /* @__PURE__ */ new Map(); - this.parameters = []; - this.capacity = size ?? 50; - if (params) { - this.parameters = params; - } - } - static { - __name(this, "EndpointCache"); - } - /** - * @param endpointParams - query for endpoint. - * @param resolver - provider of the value if not present. - * @returns endpoint corresponding to the query. - */ - get(endpointParams, resolver) { - const key = this.hash(endpointParams); - if (key === false) { - return resolver(); +var types = __nccwpck_require__(55430); + +class EndpointCache { + capacity; + data = new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } } - if (!this.data.has(key)) { - if (this.data.size > this.capacity + 10) { - const keys = this.data.keys(); - let i = 0; - while (true) { - const { value, done } = keys.next(); - this.data.delete(value); - if (done || ++i > 10) { - break; - } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); } - } - this.data.set(key, resolver()); + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); } - return this.data.get(key); - } - size() { - return this.data.size; - } - /** - * @returns cache key or false if not cachable. - */ - hash(endpointParams) { - let buffer = ""; - const { parameters } = this; - if (parameters.length === 0) { - return false; + size() { + return this.data.size; } - for (const param of parameters) { - const val = String(endpointParams[param] ?? ""); - if (val.includes("|;")) { - return false; - } - buffer += val + "|;"; + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; } - return buffer; - } -}; +} -// src/lib/isIpAddress.ts -var IP_V4_REGEX = new RegExp( - `^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$` -); -var isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); +const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); +const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); -// src/lib/isValidHostLabel.ts -var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); -var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (!allowSubDomains) { - return VALID_HOST_LABEL_REGEX.test(value); - } - const labels = value.split("."); - for (const label of labels) { - if (!isValidHostLabel(label)) { - return false; +const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +const isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); } - } - return true; -}, "isValidHostLabel"); + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}; -// src/utils/customEndpointFunctions.ts -var customEndpointFunctions = {}; +const customEndpointFunctions = {}; -// src/debug/debugId.ts -var debugId = "endpoints"; +const debugId = "endpoints"; -// src/debug/toDebugString.ts function toDebugString(input) { - if (typeof input !== "object" || input == null) { - return input; - } - if ("ref" in input) { - return `$${toDebugString(input.ref)}`; - } - if ("fn" in input) { - return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; - } - return JSON.stringify(input, null, 2); + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); } -__name(toDebugString, "toDebugString"); -// src/types/EndpointError.ts -var EndpointError = class extends Error { - static { - __name(this, "EndpointError"); - } - constructor(message) { - super(message); - this.name = "EndpointError"; - } -}; +class EndpointError extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; + } +} -// src/lib/booleanEquals.ts -var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); +const booleanEquals = (value1, value2) => value1 === value2; -// src/lib/getAttrPathList.ts -var getAttrPathList = /* @__PURE__ */ __name((path) => { - const parts = path.split("."); - const pathList = []; - for (const part of parts) { - const squareBracketIndex = part.indexOf("["); - if (squareBracketIndex !== -1) { - if (part.indexOf("]") !== part.length - 1) { - throw new EndpointError(`Path: '${path}' does not end with ']'`); - } - const arrayIndex = part.slice(squareBracketIndex + 1, -1); - if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); - } - if (squareBracketIndex !== 0) { - pathList.push(part.slice(0, squareBracketIndex)); - } - pathList.push(arrayIndex); - } else { - pathList.push(part); +const getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } + else { + pathList.push(part); + } } - } - return pathList; -}, "getAttrPathList"); + return pathList; +}; -// src/lib/getAttr.ts -var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { - if (typeof acc !== "object") { - throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); - } else if (Array.isArray(acc)) { - return acc[parseInt(index)]; - } - return acc[index]; -}, value), "getAttr"); +const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } + else if (Array.isArray(acc)) { + return acc[parseInt(index)]; + } + return acc[index]; +}, value); -// src/lib/isSet.ts -var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); +const isSet = (value) => value != null; -// src/lib/not.ts -var not = /* @__PURE__ */ __name((value) => !value, "not"); +const not = (value) => !value; -// src/lib/parseURL.ts -var import_types3 = __nccwpck_require__(55430); -var DEFAULT_PORTS = { - [import_types3.EndpointURLScheme.HTTP]: 80, - [import_types3.EndpointURLScheme.HTTPS]: 443 +const DEFAULT_PORTS = { + [types.EndpointURLScheme.HTTP]: 80, + [types.EndpointURLScheme.HTTPS]: 443, }; -var parseURL = /* @__PURE__ */ __name((value) => { - const whatwgURL = (() => { - try { - if (value instanceof URL) { - return value; - } - if (typeof value === "object" && "hostname" in value) { - const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; - const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); - url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&"); - return url; - } - return new URL(value); - } catch (error) { - return null; +const parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname, port, protocol = "", path = "", query = {} } = value; + const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query) + .map(([k, v]) => `${k}=${v}`) + .join("&"); + return url; + } + return new URL(value); + } + catch (error) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; } - })(); - if (!whatwgURL) { - console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); - return null; - } - const urlString = whatwgURL.href; - const { host, hostname, pathname, protocol, search } = whatwgURL; - if (search) { - return null; - } - const scheme = protocol.slice(0, -1); - if (!Object.values(import_types3.EndpointURLScheme).includes(scheme)) { - return null; - } - const isIp = isIpAddress(hostname); - const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); - const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; - return { - scheme, - authority, - path: pathname, - normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, - isIp - }; -}, "parseURL"); + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(types.EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || + (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp, + }; +}; -// src/lib/stringEquals.ts -var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); +const stringEquals = (value1, value2) => value1 === value2; -// src/lib/substring.ts -var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => { - if (start >= stop || input.length < stop) { - return null; - } - if (!reverse) { - return input.substring(start, stop); - } - return input.substring(input.length - stop, input.length - start); -}, "substring"); +const substring = (input, start, stop, reverse) => { + if (start >= stop || input.length < stop) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); +}; -// src/lib/uriEncode.ts -var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); +const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); -// src/utils/endpointFunctions.ts -var endpointFunctions = { - booleanEquals, - getAttr, - isSet, - isValidHostLabel, - not, - parseURL, - stringEquals, - substring, - uriEncode +const endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode, }; -// src/utils/evaluateTemplate.ts -var evaluateTemplate = /* @__PURE__ */ __name((template, options) => { - const evaluatedTemplateArr = []; - const templateContext = { - ...options.endpointParams, - ...options.referenceRecord - }; - let currentIndex = 0; - while (currentIndex < template.length) { - const openingBraceIndex = template.indexOf("{", currentIndex); - if (openingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(currentIndex)); - break; - } - evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); - const closingBraceIndex = template.indexOf("}", openingBraceIndex); - if (closingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(openingBraceIndex)); - break; - } - if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { - evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); - currentIndex = closingBraceIndex + 2; - } - const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); - if (parameterName.includes("#")) { - const [refName, attrName] = parameterName.split("#"); - evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); - } else { - evaluatedTemplateArr.push(templateContext[parameterName]); +const evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const templateContext = { + ...options.endpointParams, + ...options.referenceRecord, + }; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); + } + else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; } - currentIndex = closingBraceIndex + 1; - } - return evaluatedTemplateArr.join(""); -}, "evaluateTemplate"); - -// src/utils/getReferenceValue.ts -var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => { - const referenceRecord = { - ...options.endpointParams, - ...options.referenceRecord - }; - return referenceRecord[ref]; -}, "getReferenceValue"); - -// src/utils/evaluateExpression.ts -var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { - if (typeof obj === "string") { - return evaluateTemplate(obj, options); - } else if (obj["fn"]) { - return callFunction(obj, options); - } else if (obj["ref"]) { - return getReferenceValue(obj, options); - } - throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); -}, "evaluateExpression"); - -// src/utils/callFunction.ts -var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { - const evaluatedArgs = argv.map( - (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) - ); - const fnSegments = fn.split("."); - if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { - return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); - } - return endpointFunctions[fn](...evaluatedArgs); -}, "callFunction"); + return evaluatedTemplateArr.join(""); +}; -// src/utils/evaluateCondition.ts -var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { - if (assign && assign in options.referenceRecord) { - throw new EndpointError(`'${assign}' is already defined in Reference Record.`); - } - const value = callFunction(fnArgs, options); - options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); - return { - result: value === "" ? true : !!value, - ...assign != null && { toAssign: { name: assign, value } } - }; -}, "evaluateCondition"); - -// src/utils/evaluateConditions.ts -var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { - const conditionsReferenceRecord = {}; - for (const condition of conditions) { - const { result, toAssign } = evaluateCondition(condition, { - ...options, - referenceRecord: { +const getReferenceValue = ({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, ...options.referenceRecord, - ...conditionsReferenceRecord - } - }); - if (!result) { - return { result }; + }; + return referenceRecord[ref]; +}; + +const evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); } - if (toAssign) { - conditionsReferenceRecord[toAssign.name] = toAssign.value; - options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + else if (obj["fn"]) { + return callFunction(obj, options); } - } - return { result: true, referenceRecord: conditionsReferenceRecord }; -}, "evaluateConditions"); + else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}; + +const callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options)); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); + } + return endpointFunctions[fn](...evaluatedArgs); +}; + +const evaluateCondition = ({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...(assign != null && { toAssign: { name: assign, value } }), + }; +}; + +const evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord, + }, + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; +}; -// src/utils/getEndpointHeaders.ts -var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( - (acc, [headerKey, headerVal]) => ({ +const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ ...acc, [headerKey]: headerVal.map((headerValEntry) => { - const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); - if (typeof processedExpr !== "string") { - throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); - } - return processedExpr; - }) - }), - {} -), "getEndpointHeaders"); - -// src/utils/getEndpointProperty.ts -var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { - if (Array.isArray(property)) { - return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); - } - switch (typeof property) { - case "string": - return evaluateTemplate(property, options); - case "object": - if (property === null) { - throw new EndpointError(`Unexpected endpoint property: ${property}`); - } - return getEndpointProperties(property, options); - case "boolean": - return property; - default: - throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); - } -}, "getEndpointProperty"); + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }), +}), {}); + +const getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}; -// src/utils/getEndpointProperties.ts -var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( - (acc, [propertyKey, propertyVal]) => ({ +const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ ...acc, - [propertyKey]: getEndpointProperty(propertyVal, options) - }), - {} -), "getEndpointProperties"); + [propertyKey]: getEndpointProperty(propertyVal, options), +}), {}); -// src/utils/getEndpointUrl.ts -var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { - const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); - if (typeof expression === "string") { - try { - return new URL(expression); - } catch (error) { - console.error(`Failed to construct URL with ${expression}`, error); - throw error; +const getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } + catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } } - } - throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); -}, "getEndpointUrl"); - -// src/utils/evaluateEndpointRule.ts -var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { - const { conditions, endpoint } = endpointRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - const endpointRuleOptions = { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }; - const { url, properties, headers } = endpoint; - options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); - return { - ...headers != void 0 && { - headers: getEndpointHeaders(headers, endpointRuleOptions) - }, - ...properties != void 0 && { - properties: getEndpointProperties(properties, endpointRuleOptions) - }, - url: getEndpointUrl(url, endpointRuleOptions) - }; -}, "evaluateEndpointRule"); + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}; -// src/utils/evaluateErrorRule.ts -var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { - const { conditions, error } = errorRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - throw new EndpointError( - evaluateExpression(error, "Error", { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }) - ); -}, "evaluateErrorRule"); +const evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...(headers != undefined && { + headers: getEndpointHeaders(headers, endpointRuleOptions), + }), + ...(properties != undefined && { + properties: getEndpointProperties(properties, endpointRuleOptions), + }), + url: getEndpointUrl(url, endpointRuleOptions), + }; +}; -// src/utils/evaluateTreeRule.ts -var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { - const { conditions, rules } = treeRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - return evaluateRules(rules, { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }); -}, "evaluateTreeRule"); - -// src/utils/evaluateRules.ts -var evaluateRules = /* @__PURE__ */ __name((rules, options) => { - for (const rule of rules) { - if (rule.type === "endpoint") { - const endpointOrUndefined = evaluateEndpointRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } else if (rule.type === "error") { - evaluateErrorRule(rule, options); - } else if (rule.type === "tree") { - const endpointOrUndefined = evaluateTreeRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } else { - throw new EndpointError(`Unknown endpoint rule: ${rule}`); +const evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - } - throw new EndpointError(`Rules evaluation failed`); -}, "evaluateRules"); + throw new EndpointError(evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + })); +}; -// src/resolveEndpoint.ts -var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { - const { endpointParams, logger } = options; - const { parameters, rules } = ruleSetObject; - options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); - const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]); - if (paramsWithDefault.length > 0) { - for (const [paramKey, paramDefaultValue] of paramsWithDefault) { - endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; +const evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - } - const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); - for (const requiredParam of requiredParams) { - if (endpointParams[requiredParam] == null) { - throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + return evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }); +}; + +const evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } + else if (rule.type === "tree") { + const endpointOrUndefined = evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } } - } - const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); - options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); - return endpoint; -}, "resolveEndpoint"); -// Annotate the CommonJS export names for ESM import in node: + throw new EndpointError(`Rules evaluation failed`); +}; -0 && (0); +const resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters) + .filter(([, v]) => v.default != null) + .map(([k, v]) => [k, v.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } + } + const requiredParams = Object.entries(parameters) + .filter(([, v]) => v.required) + .map(([k]) => k); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}; +exports.EndpointCache = EndpointCache; +exports.EndpointError = EndpointError; +exports.customEndpointFunctions = customEndpointFunctions; +exports.isIpAddress = isIpAddress; +exports.isValidHostLabel = isValidHostLabel; +exports.resolveEndpoint = resolveEndpoint; /***/ }), /***/ 55430: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); +/***/ ((__unused_webpack_module, exports) => { -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +"use strict"; -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "sha256" /* SHA256 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.sha256, "checksumConstructor") - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: /* @__PURE__ */ __name(() => "md5" /* MD5 */, "algorithmId"), - checksumConstructor: /* @__PURE__ */ __name(() => runtimeConfig.md5, "checksumConstructor") - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +const SMITHY_CONTEXT_KEY = "__smithy_context"; -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); -0 && (0); +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), @@ -91719,349 +84098,287 @@ __name(toHex, "toHex"); /***/ }), /***/ 15518: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, - DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, - DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, - DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, - DefaultRateLimiter: () => DefaultRateLimiter, - INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, - INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, - MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, - NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, - REQUEST_HEADER: () => REQUEST_HEADER, - RETRY_COST: () => RETRY_COST, - RETRY_MODES: () => RETRY_MODES, - StandardRetryStrategy: () => StandardRetryStrategy, - THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, - TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST -}); -module.exports = __toCommonJS(index_exports); -// src/config.ts -var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { - RETRY_MODES2["STANDARD"] = "standard"; - RETRY_MODES2["ADAPTIVE"] = "adaptive"; - return RETRY_MODES2; -})(RETRY_MODES || {}); -var DEFAULT_MAX_ATTEMPTS = 3; -var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; - -// src/DefaultRateLimiter.ts -var import_service_error_classification = __nccwpck_require__(42058); -var DefaultRateLimiter = class _DefaultRateLimiter { - constructor(options) { - // Pre-set state variables - this.currentCapacity = 0; - this.enabled = false; - this.lastMaxRate = 0; - this.measuredTxRate = 0; - this.requestCount = 0; - this.lastTimestamp = 0; - this.timeWindow = 0; - this.beta = options?.beta ?? 0.7; - this.minCapacity = options?.minCapacity ?? 1; - this.minFillRate = options?.minFillRate ?? 0.5; - this.scaleConstant = options?.scaleConstant ?? 0.4; - this.smooth = options?.smooth ?? 0.8; - const currentTimeInSeconds = this.getCurrentTimeInSeconds(); - this.lastThrottleTime = currentTimeInSeconds; - this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); - this.fillRate = this.minFillRate; - this.maxCapacity = this.minCapacity; - } - static { - __name(this, "DefaultRateLimiter"); - } - static { - /** - * Only used in testing. - */ - this.setTimeoutFn = setTimeout; - } - getCurrentTimeInSeconds() { - return Date.now() / 1e3; - } - async getSendToken() { - return this.acquireTokenBucket(1); - } - async acquireTokenBucket(amount) { - if (!this.enabled) { - return; +var serviceErrorClassification = __nccwpck_require__(42058); + +exports.RETRY_MODES = void 0; +(function (RETRY_MODES) { + RETRY_MODES["STANDARD"] = "standard"; + RETRY_MODES["ADAPTIVE"] = "adaptive"; +})(exports.RETRY_MODES || (exports.RETRY_MODES = {})); +const DEFAULT_MAX_ATTEMPTS = 3; +const DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD; + +class DefaultRateLimiter { + static setTimeoutFn = setTimeout; + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + currentCapacity = 0; + enabled = false; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + const currentTimeInSeconds = this.getCurrentTimeInSeconds(); + this.lastThrottleTime = currentTimeInSeconds; + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + getCurrentTimeInSeconds() { + return Date.now() / 1000; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + if (amount > this.currentCapacity) { + const delay = ((amount - this.currentCapacity) / this.fillRate) * 1000; + await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay)); + } + this.currentCapacity = this.currentCapacity - amount; } - this.refillTokenBucket(); - if (amount > this.currentCapacity) { - const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; - await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); + refillTokenBucket() { + const timestamp = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp; + return; + } + const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; + this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); + this.lastTimestamp = timestamp; + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + if (serviceErrorClassification.isThrottlingError(response)) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } + else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); } - this.currentCapacity = this.currentCapacity - amount; - } - refillTokenBucket() { - const timestamp = this.getCurrentTimeInSeconds(); - if (!this.lastTimestamp) { - this.lastTimestamp = timestamp; - return; + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); } - const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; - this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); - this.lastTimestamp = timestamp; - } - updateClientSendingRate(response) { - let calculatedRate; - this.updateMeasuredRate(); - if ((0, import_service_error_classification.isThrottlingError)(response)) { - const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); - this.lastMaxRate = rateToUse; - this.calculateTimeWindow(); - this.lastThrottleTime = this.getCurrentTimeInSeconds(); - calculatedRate = this.cubicThrottle(rateToUse); - this.enableTokenBucket(); - } else { - this.calculateTimeWindow(); - calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); } - const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); - this.updateTokenBucketRate(newRate); - } - calculateTimeWindow() { - this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); - } - cubicThrottle(rateToUse) { - return this.getPrecise(rateToUse * this.beta); - } - cubicSuccess(timestamp) { - return this.getPrecise( - this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate - ); - } - enableTokenBucket() { - this.enabled = true; - } - updateTokenBucketRate(newRate) { - this.refillTokenBucket(); - this.fillRate = Math.max(newRate, this.minFillRate); - this.maxCapacity = Math.max(newRate, this.minCapacity); - this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); - } - updateMeasuredRate() { - const t = this.getCurrentTimeInSeconds(); - const timeBucket = Math.floor(t * 2) / 2; - this.requestCount++; - if (timeBucket > this.lastTxRateBucket) { - const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); - this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); - this.requestCount = 0; - this.lastTxRateBucket = timeBucket; + cubicSuccess(timestamp) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); } - } - getPrecise(num) { - return parseFloat(num.toFixed(8)); - } -}; - -// src/constants.ts -var DEFAULT_RETRY_DELAY_BASE = 100; -var MAXIMUM_RETRY_DELAY = 20 * 1e3; -var THROTTLING_RETRY_DELAY_BASE = 500; -var INITIAL_RETRY_TOKENS = 500; -var RETRY_COST = 5; -var TIMEOUT_RETRY_COST = 10; -var NO_RETRY_INCREMENT = 1; -var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; -var REQUEST_HEADER = "amz-sdk-request"; - -// src/defaultRetryBackoffStrategy.ts -var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { - let delayBase = DEFAULT_RETRY_DELAY_BASE; - const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { - return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - }, "computeNextBackoffDelay"); - const setDelayBase = /* @__PURE__ */ __name((delay) => { - delayBase = delay; - }, "setDelayBase"); - return { - computeNextBackoffDelay, - setDelayBase - }; -}, "getDefaultRetryBackoffStrategy"); - -// src/defaultRetryToken.ts -var createDefaultRetryToken = /* @__PURE__ */ __name(({ - retryDelay, - retryCount, - retryCost -}) => { - const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); - const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); - const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); - return { - getRetryCount, - getRetryDelay, - getRetryCost - }; -}, "createDefaultRetryToken"); - -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttempts) { - this.maxAttempts = maxAttempts; - this.mode = "standard" /* STANDARD */; - this.capacity = INITIAL_RETRY_TOKENS; - this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); - this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; - } - static { - __name(this, "StandardRetryStrategy"); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async acquireInitialRetryToken(retryTokenScope) { - return createDefaultRetryToken({ - retryDelay: DEFAULT_RETRY_DELAY_BASE, - retryCount: 0 - }); - } - async refreshRetryTokenForRetry(token, errorInfo) { - const maxAttempts = await this.getMaxAttempts(); - if (this.shouldRetry(token, errorInfo, maxAttempts)) { - const errorType = errorInfo.errorType; - this.retryBackoffStrategy.setDelayBase( - errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE - ); - const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); - const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; - const capacityCost = this.getCapacityCost(errorType); - this.capacity -= capacityCost; - return createDefaultRetryToken({ - retryDelay, - retryCount: token.getRetryCount() + 1, - retryCost: capacityCost - }); + enableTokenBucket() { + this.enabled = true; } - throw new Error("No retry token available"); - } - recordSuccess(token) { - this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); - } - /** - * @returns the current available retry capacity. - * - * This number decreases when retries are executed and refills when requests or retries succeed. - */ - getCapacity() { - return this.capacity; - } - async getMaxAttempts() { - try { - return await this.maxAttemptsProvider(); - } catch (error) { - console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); - return DEFAULT_MAX_ATTEMPTS; + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); } - } - shouldRetry(tokenToRenew, errorInfo, maxAttempts) { - const attempts = tokenToRenew.getRetryCount() + 1; - return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); - } - getCapacityCost(errorType) { - return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; - } - isRetryableError(errorType) { - return errorType === "THROTTLING" || errorType === "TRANSIENT"; - } + updateMeasuredRate() { + const t = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } +} + +const DEFAULT_RETRY_DELAY_BASE = 100; +const MAXIMUM_RETRY_DELAY = 20 * 1000; +const THROTTLING_RETRY_DELAY_BASE = 500; +const INITIAL_RETRY_TOKENS = 500; +const RETRY_COST = 5; +const TIMEOUT_RETRY_COST = 10; +const NO_RETRY_INCREMENT = 1; +const INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +const REQUEST_HEADER = "amz-sdk-request"; + +const getDefaultRetryBackoffStrategy = () => { + let delayBase = DEFAULT_RETRY_DELAY_BASE; + const computeNextBackoffDelay = (attempts) => { + return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + }; + const setDelayBase = (delay) => { + delayBase = delay; + }; + return { + computeNextBackoffDelay, + setDelayBase, + }; }; -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = "adaptive" /* ADAPTIVE */; - const { rateLimiter } = options ?? {}; - this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); - this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); - } - static { - __name(this, "AdaptiveRetryStrategy"); - } - async acquireInitialRetryToken(retryTokenScope) { - await this.rateLimiter.getSendToken(); - return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - this.rateLimiter.updateClientSendingRate(errorInfo); - return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - } - recordSuccess(token) { - this.rateLimiter.updateClientSendingRate({}); - this.standardRetryStrategy.recordSuccess(token); - } +const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost, }) => { + const getRetryCount = () => retryCount; + const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay); + const getRetryCost = () => retryCost; + return { + getRetryCount, + getRetryDelay, + getRetryCost, + }; }; -// src/ConfiguredRetryStrategy.ts -var ConfiguredRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "ConfiguredRetryStrategy"); - } - /** - * @param maxAttempts - the maximum number of retry attempts allowed. - * e.g., if set to 3, then 4 total requests are possible. - * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt - * and returns the delay. - * - * @example exponential backoff. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) - * }); - * ``` - * @example constant delay. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, 2000) - * }); - * ``` - */ - constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { - super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); - if (typeof computeNextBackoffDelay === "number") { - this.computeNextBackoffDelay = () => computeNextBackoffDelay; - } else { - this.computeNextBackoffDelay = computeNextBackoffDelay; +class StandardRetryStrategy { + maxAttempts; + mode = exports.RETRY_MODES.STANDARD; + capacity = INITIAL_RETRY_TOKENS; + retryBackoffStrategy = getDefaultRetryBackoffStrategy(); + maxAttemptsProvider; + constructor(maxAttempts) { + this.maxAttempts = maxAttempts; + this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; + } + async acquireInitialRetryToken(retryTokenScope) { + return createDefaultRetryToken({ + retryDelay: DEFAULT_RETRY_DELAY_BASE, + retryCount: 0, + }); } - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); - return token; - } -}; -// Annotate the CommonJS export names for ESM import in node: + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + if (this.shouldRetry(token, errorInfo, maxAttempts)) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + const retryDelay = errorInfo.retryAfterHint + ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) + : delayFromErrorType; + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + return createDefaultRetryToken({ + retryDelay, + retryCount: token.getRetryCount() + 1, + retryCost: capacityCost, + }); + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } + catch (error) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + shouldRetry(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + return (attempts < maxAttempts && + this.capacity >= this.getCapacityCost(errorInfo.errorType) && + this.isRetryableError(errorInfo.errorType)); + } + getCapacityCost(errorType) { + return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +} -0 && (0); +class AdaptiveRetryStrategy { + maxAttemptsProvider; + rateLimiter; + standardRetryStrategy; + mode = exports.RETRY_MODES.ADAPTIVE; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + await this.rateLimiter.getSendToken(); + return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } +} + +class ConfiguredRetryStrategy extends StandardRetryStrategy { + computeNextBackoffDelay; + constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } + else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); + return token; + } +} +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; +exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; +exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; +exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE; +exports.DefaultRateLimiter = DefaultRateLimiter; +exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; +exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; +exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; +exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; +exports.REQUEST_HEADER = REQUEST_HEADER; +exports.RETRY_COST = RETRY_COST; +exports.StandardRetryStrategy = StandardRetryStrategy; +exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; +exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; /***/ }), @@ -92762,207 +85079,234 @@ var toUtf8 = /* @__PURE__ */ __name((input) => { /***/ }), /***/ 95290: -/***/ ((module) => { +/***/ ((__unused_webpack_module, exports) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var index_exports = {}; -__export(index_exports, { - WaiterState: () => WaiterState, - checkExceptions: () => checkExceptions, - createWaiter: () => createWaiter, - waiterServiceDefaults: () => waiterServiceDefaults -}); -module.exports = __toCommonJS(index_exports); -// src/utils/sleep.ts -var sleep = /* @__PURE__ */ __name((seconds) => { - return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); -}, "sleep"); - -// src/waiter.ts -var waiterServiceDefaults = { - minDelay: 2, - maxDelay: 120 -}; -var WaiterState = /* @__PURE__ */ ((WaiterState2) => { - WaiterState2["ABORTED"] = "ABORTED"; - WaiterState2["FAILURE"] = "FAILURE"; - WaiterState2["SUCCESS"] = "SUCCESS"; - WaiterState2["RETRY"] = "RETRY"; - WaiterState2["TIMEOUT"] = "TIMEOUT"; - return WaiterState2; -})(WaiterState || {}); -var checkExceptions = /* @__PURE__ */ __name((result) => { - if (result.state === "ABORTED" /* ABORTED */) { - const abortError = new Error( - `${JSON.stringify({ - ...result, - reason: "Request was aborted" - })}` - ); - abortError.name = "AbortError"; - throw abortError; - } else if (result.state === "TIMEOUT" /* TIMEOUT */) { - const timeoutError = new Error( - `${JSON.stringify({ - ...result, - reason: "Waiter has timed out" - })}` - ); - timeoutError.name = "TimeoutError"; - throw timeoutError; - } else if (result.state !== "SUCCESS" /* SUCCESS */) { - throw new Error(`${JSON.stringify(result)}`); - } - return result; -}, "checkExceptions"); - -// src/poller.ts -var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { - if (attempt > attemptCeiling) return maxDelay; - const delay = minDelay * 2 ** (attempt - 1); - return randomInRange(minDelay, delay); -}, "exponentialBackoffWithJitter"); -var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); -var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { - const observedResponses = {}; - const { state, reason } = await acceptorChecks(client, input); - if (reason) { - const message = createMessageFromResponse(reason); - observedResponses[message] |= 0; - observedResponses[message] += 1; - } - if (state !== "RETRY" /* RETRY */) { - return { state, reason, observedResponses }; - } - let currentAttempt = 1; - const waitUntil = Date.now() + maxWaitTime * 1e3; - const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; - while (true) { - if (abortController?.signal?.aborted || abortSignal?.aborted) { - const message = "AbortController signal aborted."; - observedResponses[message] |= 0; - observedResponses[message] += 1; - return { state: "ABORTED" /* ABORTED */, observedResponses }; - } - const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); - if (Date.now() + delay * 1e3 > waitUntil) { - return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; - } - await sleep(delay); - const { state: state2, reason: reason2 } = await acceptorChecks(client, input); - if (reason2) { - const message = createMessageFromResponse(reason2); - observedResponses[message] |= 0; - observedResponses[message] += 1; - } - if (state2 !== "RETRY" /* RETRY */) { - return { state: state2, reason: reason2, observedResponses }; - } - currentAttempt += 1; - } -}, "runPolling"); -var createMessageFromResponse = /* @__PURE__ */ __name((reason) => { - if (reason?.$responseBodyText) { - return `Deserialization error for body: ${reason.$responseBodyText}`; - } - if (reason?.$metadata?.httpStatusCode) { - if (reason.$response || reason.message) { - return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; - } - return `${reason.$metadata.httpStatusCode}: OK`; - } - return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); -}, "createMessageFromResponse"); - -// src/utils/validate.ts -var validateWaiterOptions = /* @__PURE__ */ __name((options) => { - if (options.maxWaitTime <= 0) { - throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); - } else if (options.minDelay <= 0) { - throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); - } else if (options.maxDelay <= 0) { - throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); - } else if (options.maxWaitTime <= options.minDelay) { - throw new Error( - `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); - } else if (options.maxDelay < options.minDelay) { - throw new Error( - `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); - } -}, "validateWaiterOptions"); +const sleep = (seconds) => { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); +}; -// src/createWaiter.ts -var abortTimeout = /* @__PURE__ */ __name((abortSignal) => { - let onAbort; - const promise = new Promise((resolve) => { - onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - abortSignal.addEventListener("abort", onAbort); - } else { - abortSignal.onabort = onAbort; +const waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120, +}; +exports.WaiterState = void 0; +(function (WaiterState) { + WaiterState["ABORTED"] = "ABORTED"; + WaiterState["FAILURE"] = "FAILURE"; + WaiterState["SUCCESS"] = "SUCCESS"; + WaiterState["RETRY"] = "RETRY"; + WaiterState["TIMEOUT"] = "TIMEOUT"; +})(exports.WaiterState || (exports.WaiterState = {})); +const checkExceptions = (result) => { + if (result.state === exports.WaiterState.ABORTED) { + const abortError = new Error(`${JSON.stringify({ + ...result, + reason: "Request was aborted", + })}`); + abortError.name = "AbortError"; + throw abortError; } - }); - return { - clearListener() { - if (typeof abortSignal.removeEventListener === "function") { - abortSignal.removeEventListener("abort", onAbort); - } - }, - aborted: promise - }; -}, "abortTimeout"); -var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { - const params = { - ...waiterServiceDefaults, - ...options - }; - validateWaiterOptions(params); - const exitConditions = [runPolling(params, input, acceptorChecks)]; - const finalize = []; - if (options.abortSignal) { - const { aborted, clearListener } = abortTimeout(options.abortSignal); - finalize.push(clearListener); - exitConditions.push(aborted); - } - if (options.abortController?.signal) { - const { aborted, clearListener } = abortTimeout(options.abortController.signal); - finalize.push(clearListener); - exitConditions.push(aborted); - } - return Promise.race(exitConditions).then((result) => { - for (const fn of finalize) { - fn(); + else if (result.state === exports.WaiterState.TIMEOUT) { + const timeoutError = new Error(`${JSON.stringify({ + ...result, + reason: "Waiter has timed out", + })}`); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } + else if (result.state !== exports.WaiterState.SUCCESS) { + throw new Error(`${JSON.stringify(result)}`); } return result; - }); -}, "createWaiter"); -// Annotate the CommonJS export names for ESM import in node: +}; -0 && (0); +const exponentialBackoffWithJitter = (minDelay, maxDelay, attemptCeiling, attempt) => { + if (attempt > attemptCeiling) + return maxDelay; + const delay = minDelay * 2 ** (attempt - 1); + return randomInRange(minDelay, delay); +}; +const randomInRange = (min, max) => min + Math.random() * (max - min); +const runPolling = async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state !== exports.WaiterState.RETRY) { + return { state, reason, observedResponses }; + } + let currentAttempt = 1; + const waitUntil = Date.now() + maxWaitTime * 1000; + const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; + while (true) { + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message = "AbortController signal aborted."; + observedResponses[message] |= 0; + observedResponses[message] += 1; + return { state: exports.WaiterState.ABORTED, observedResponses }; + } + const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); + if (Date.now() + delay * 1000 > waitUntil) { + return { state: exports.WaiterState.TIMEOUT, observedResponses }; + } + await sleep(delay); + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state !== exports.WaiterState.RETRY) { + return { state, reason, observedResponses }; + } + currentAttempt += 1; + } +}; +const createMessageFromResponse = (reason) => { + if (reason?.$responseBodyText) { + return `Deserialization error for body: ${reason.$responseBodyText}`; + } + if (reason?.$metadata?.httpStatusCode) { + if (reason.$response || reason.message) { + return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; + } + return `${reason.$metadata.httpStatusCode}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); +}; + +const validateWaiterOptions = (options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } + else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } + else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } + else if (options.maxWaitTime <= options.minDelay) { + throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } + else if (options.maxDelay < options.minDelay) { + throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } +}; + +const abortTimeout = (abortSignal) => { + let onAbort; + const promise = new Promise((resolve) => { + onAbort = () => resolve({ state: exports.WaiterState.ABORTED }); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + }); + return { + clearListener() { + if (typeof abortSignal.removeEventListener === "function") { + abortSignal.removeEventListener("abort", onAbort); + } + }, + aborted: promise, + }; +}; +const createWaiter = async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options, + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + const finalize = []; + if (options.abortSignal) { + const { aborted, clearListener } = abortTimeout(options.abortSignal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + if (options.abortController?.signal) { + const { aborted, clearListener } = abortTimeout(options.abortController.signal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + return Promise.race(exitConditions).then((result) => { + for (const fn of finalize) { + fn(); + } + return result; + }); +}; + +exports.checkExceptions = checkExceptions; +exports.createWaiter = createWaiter; +exports.waiterServiceDefaults = waiterServiceDefaults; +/***/ }), + +/***/ 90266: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var randomUUID = __nccwpck_require__(8492); + +const decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +const v4 = () => { + if (randomUUID.randomUUID) { + return randomUUID.randomUUID(); + } + const rnds = new Uint8Array(16); + crypto.getRandomValues(rnds); + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + return (decimalToHex[rnds[0]] + + decimalToHex[rnds[1]] + + decimalToHex[rnds[2]] + + decimalToHex[rnds[3]] + + "-" + + decimalToHex[rnds[4]] + + decimalToHex[rnds[5]] + + "-" + + decimalToHex[rnds[6]] + + decimalToHex[rnds[7]] + + "-" + + decimalToHex[rnds[8]] + + decimalToHex[rnds[9]] + + "-" + + decimalToHex[rnds[10]] + + decimalToHex[rnds[11]] + + decimalToHex[rnds[12]] + + decimalToHex[rnds[13]] + + decimalToHex[rnds[14]] + + decimalToHex[rnds[15]]); +}; + +exports.v4 = v4; + + +/***/ }), + +/***/ 8492: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.randomUUID = void 0; +const tslib_1 = __nccwpck_require__(61860); +const crypto_1 = tslib_1.__importDefault(__nccwpck_require__(76982)); +exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default); + /***/ }), @@ -116681,6 +109025,14 @@ module.exports = require("node:events"); /***/ }), +/***/ 73024: +/***/ ((module) => { + +"use strict"; +module.exports = require("node:fs"); + +/***/ }), + /***/ 57075: /***/ ((module) => { @@ -118442,7 +110794,7 @@ module.exports = parseParams /***/ }), -/***/ 79730: +/***/ 57349: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -118601,7 +110953,7 @@ exports.composeDoc = composeDoc; var Alias = __nccwpck_require__(4065); var identity = __nccwpck_require__(41127); -var composeCollection = __nccwpck_require__(79730); +var composeCollection = __nccwpck_require__(57349); var composeScalar = __nccwpck_require__(5413); var resolveEnd = __nccwpck_require__(17788); var utilEmptyScalarPosition = __nccwpck_require__(22599); @@ -127052,27 +119404,11 @@ module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/client-codedeploy"," /***/ }), -/***/ 36948: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/client-sso","description":"AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native","version":"3.888.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-sso","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo sso"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.888.0","@aws-sdk/middleware-host-header":"3.887.0","@aws-sdk/middleware-logger":"3.887.0","@aws-sdk/middleware-recursion-detection":"3.887.0","@aws-sdk/middleware-user-agent":"3.888.0","@aws-sdk/region-config-resolver":"3.887.0","@aws-sdk/types":"3.887.0","@aws-sdk/util-endpoints":"3.887.0","@aws-sdk/util-user-agent-browser":"3.887.0","@aws-sdk/util-user-agent-node":"3.888.0","@smithy/config-resolver":"^4.2.1","@smithy/core":"^3.11.0","@smithy/fetch-http-handler":"^5.2.1","@smithy/hash-node":"^4.1.1","@smithy/invalid-dependency":"^4.1.1","@smithy/middleware-content-length":"^4.1.1","@smithy/middleware-endpoint":"^4.2.1","@smithy/middleware-retry":"^4.2.1","@smithy/middleware-serde":"^4.1.1","@smithy/middleware-stack":"^4.1.1","@smithy/node-config-provider":"^4.2.1","@smithy/node-http-handler":"^4.2.1","@smithy/protocol-http":"^5.2.1","@smithy/smithy-client":"^4.6.1","@smithy/types":"^4.5.0","@smithy/url-parser":"^4.1.1","@smithy/util-base64":"^4.1.0","@smithy/util-body-length-browser":"^4.1.0","@smithy/util-body-length-node":"^4.1.0","@smithy/util-defaults-mode-browser":"^4.1.1","@smithy/util-defaults-mode-node":"^4.1.1","@smithy/util-endpoints":"^3.1.1","@smithy/util-middleware":"^4.1.1","@smithy/util-retry":"^4.1.1","@smithy/util-utf8":"^4.1.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-sso"}}'); - -/***/ }), - -/***/ 77507: -/***/ ((module) => { - -"use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.888.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.888.0","@aws-sdk/middleware-host-header":"3.887.0","@aws-sdk/middleware-logger":"3.887.0","@aws-sdk/middleware-recursion-detection":"3.887.0","@aws-sdk/middleware-user-agent":"3.888.0","@aws-sdk/region-config-resolver":"3.887.0","@aws-sdk/types":"3.887.0","@aws-sdk/util-endpoints":"3.887.0","@aws-sdk/util-user-agent-browser":"3.887.0","@aws-sdk/util-user-agent-node":"3.888.0","@smithy/config-resolver":"^4.2.1","@smithy/core":"^3.11.0","@smithy/fetch-http-handler":"^5.2.1","@smithy/hash-node":"^4.1.1","@smithy/invalid-dependency":"^4.1.1","@smithy/middleware-content-length":"^4.1.1","@smithy/middleware-endpoint":"^4.2.1","@smithy/middleware-retry":"^4.2.1","@smithy/middleware-serde":"^4.1.1","@smithy/middleware-stack":"^4.1.1","@smithy/node-config-provider":"^4.2.1","@smithy/node-http-handler":"^4.2.1","@smithy/protocol-http":"^5.2.1","@smithy/smithy-client":"^4.6.1","@smithy/types":"^4.5.0","@smithy/url-parser":"^4.1.1","@smithy/util-base64":"^4.1.0","@smithy/util-body-length-browser":"^4.1.0","@smithy/util-body-length-node":"^4.1.0","@smithy/util-defaults-mode-browser":"^4.1.1","@smithy/util-defaults-mode-node":"^4.1.1","@smithy/util-endpoints":"^3.1.1","@smithy/util-middleware":"^4.1.1","@smithy/util-retry":"^4.1.1","@smithy/util-utf8":"^4.1.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); - -/***/ }), - /***/ 51194: /***/ ((module) => { "use strict"; -module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/client-ecs","description":"AWS SDK for JavaScript Ecs Client for Node.js, Browser and React Native","version":"3.888.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-ecs","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo ecs"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.888.0","@aws-sdk/credential-provider-node":"3.888.0","@aws-sdk/middleware-host-header":"3.887.0","@aws-sdk/middleware-logger":"3.887.0","@aws-sdk/middleware-recursion-detection":"3.887.0","@aws-sdk/middleware-user-agent":"3.888.0","@aws-sdk/region-config-resolver":"3.887.0","@aws-sdk/types":"3.887.0","@aws-sdk/util-endpoints":"3.887.0","@aws-sdk/util-user-agent-browser":"3.887.0","@aws-sdk/util-user-agent-node":"3.888.0","@smithy/config-resolver":"^4.2.1","@smithy/core":"^3.11.0","@smithy/fetch-http-handler":"^5.2.1","@smithy/hash-node":"^4.1.1","@smithy/invalid-dependency":"^4.1.1","@smithy/middleware-content-length":"^4.1.1","@smithy/middleware-endpoint":"^4.2.1","@smithy/middleware-retry":"^4.2.1","@smithy/middleware-serde":"^4.1.1","@smithy/middleware-stack":"^4.1.1","@smithy/node-config-provider":"^4.2.1","@smithy/node-http-handler":"^4.2.1","@smithy/protocol-http":"^5.2.1","@smithy/smithy-client":"^4.6.1","@smithy/types":"^4.5.0","@smithy/url-parser":"^4.1.1","@smithy/util-base64":"^4.1.0","@smithy/util-body-length-browser":"^4.1.0","@smithy/util-body-length-node":"^4.1.0","@smithy/util-defaults-mode-browser":"^4.1.1","@smithy/util-defaults-mode-node":"^4.1.1","@smithy/util-endpoints":"^3.1.1","@smithy/util-middleware":"^4.1.1","@smithy/util-retry":"^4.1.1","@smithy/util-utf8":"^4.1.0","@smithy/util-waiter":"^4.1.1","@types/uuid":"^9.0.1","tslib":"^2.6.2","uuid":"^9.0.1"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-ecs","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-ecs"}}'); +module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/client-ecs","description":"AWS SDK for JavaScript Ecs Client for Node.js, Browser and React Native","version":"3.908.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-ecs","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo ecs"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.908.0","@aws-sdk/credential-provider-node":"3.908.0","@aws-sdk/middleware-host-header":"3.901.0","@aws-sdk/middleware-logger":"3.901.0","@aws-sdk/middleware-recursion-detection":"3.901.0","@aws-sdk/middleware-user-agent":"3.908.0","@aws-sdk/region-config-resolver":"3.901.0","@aws-sdk/types":"3.901.0","@aws-sdk/util-endpoints":"3.901.0","@aws-sdk/util-user-agent-browser":"3.907.0","@aws-sdk/util-user-agent-node":"3.908.0","@smithy/config-resolver":"^4.3.0","@smithy/core":"^3.15.0","@smithy/fetch-http-handler":"^5.3.1","@smithy/hash-node":"^4.2.0","@smithy/invalid-dependency":"^4.2.0","@smithy/middleware-content-length":"^4.2.0","@smithy/middleware-endpoint":"^4.3.1","@smithy/middleware-retry":"^4.4.1","@smithy/middleware-serde":"^4.2.0","@smithy/middleware-stack":"^4.2.0","@smithy/node-config-provider":"^4.3.0","@smithy/node-http-handler":"^4.3.0","@smithy/protocol-http":"^5.3.0","@smithy/smithy-client":"^4.7.1","@smithy/types":"^4.6.0","@smithy/url-parser":"^4.2.0","@smithy/util-base64":"^4.3.0","@smithy/util-body-length-browser":"^4.2.0","@smithy/util-body-length-node":"^4.2.1","@smithy/util-defaults-mode-browser":"^4.3.0","@smithy/util-defaults-mode-node":"^4.2.1","@smithy/util-endpoints":"^3.2.0","@smithy/util-middleware":"^4.2.0","@smithy/util-retry":"^4.2.0","@smithy/util-utf8":"^4.2.0","@smithy/util-waiter":"^4.2.0","@smithy/uuid":"^1.1.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-ecs","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-ecs"}}'); /***/ }), @@ -127124,11 +119460,136 @@ module.exports = /*#__PURE__*/JSON.parse('{"name":"@aws-sdk/nested-clients","ver /******/ return module.exports; /******/ } /******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __nccwpck_require__.m = __webpack_modules__; +/******/ /************************************************************************/ +/******/ /* webpack/runtime/create fake namespace object */ +/******/ (() => { +/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); +/******/ var leafPrototypes; +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 16: return value when it's Promise-like +/******/ // mode & 8|1: behave like require +/******/ __nccwpck_require__.t = function(value, mode) { +/******/ if(mode & 1) value = this(value); +/******/ if(mode & 8) return value; +/******/ if(typeof value === 'object' && value) { +/******/ if((mode & 4) && value.__esModule) return value; +/******/ if((mode & 16) && typeof value.then === 'function') return value; +/******/ } +/******/ var ns = Object.create(null); +/******/ __nccwpck_require__.r(ns); +/******/ var def = {}; +/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; +/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { +/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); +/******/ } +/******/ def['default'] = () => (value); +/******/ __nccwpck_require__.d(ns, def); +/******/ return ns; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __nccwpck_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/ensure chunk */ +/******/ (() => { +/******/ __nccwpck_require__.f = {}; +/******/ // This file contains only the entry chunk. +/******/ // The chunk loading function for additional chunks +/******/ __nccwpck_require__.e = (chunkId) => { +/******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => { +/******/ __nccwpck_require__.f[key](chunkId, promises); +/******/ return promises; +/******/ }, [])); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/get javascript chunk filename */ +/******/ (() => { +/******/ // This function allow to reference async chunks +/******/ __nccwpck_require__.u = (chunkId) => { +/******/ // return url for filenames based on template +/******/ return "" + chunkId + ".index.js"; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __nccwpck_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ +/******/ /* webpack/runtime/require chunk loading */ +/******/ (() => { +/******/ // no baseURI +/******/ +/******/ // object to store loaded chunks +/******/ // "1" means "loaded", otherwise not loaded yet +/******/ var installedChunks = { +/******/ 792: 1 +/******/ }; +/******/ +/******/ // no on chunks loaded +/******/ +/******/ var installChunk = (chunk) => { +/******/ var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime; +/******/ for(var moduleId in moreModules) { +/******/ if(__nccwpck_require__.o(moreModules, moduleId)) { +/******/ __nccwpck_require__.m[moduleId] = moreModules[moduleId]; +/******/ } +/******/ } +/******/ if(runtime) runtime(__nccwpck_require__); +/******/ for(var i = 0; i < chunkIds.length; i++) +/******/ installedChunks[chunkIds[i]] = 1; +/******/ +/******/ }; +/******/ +/******/ // require() chunk loading for javascript +/******/ __nccwpck_require__.f.require = (chunkId, promises) => { +/******/ // "1" is the signal for "already loaded" +/******/ if(!installedChunks[chunkId]) { +/******/ if(true) { // all chunks have JS +/******/ installChunk(require("./" + __nccwpck_require__.u(chunkId))); +/******/ } else installedChunks[chunkId] = 1; +/******/ } +/******/ }; +/******/ +/******/ // no external install chunk +/******/ +/******/ // no HMR +/******/ +/******/ // no HMR manifest +/******/ })(); +/******/ /************************************************************************/ /******/ /******/ // startup diff --git a/package-lock.json b/package-lock.json index e8a7958d..8170c3bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@actions/core": "^1.10.1", "@aws-sdk/client-codedeploy": "^3.888.0", - "@aws-sdk/client-ecs": "^3.883.0", + "@aws-sdk/client-ecs": "^3.908.0", "yaml": "^2.8.1" }, "devDependencies": { @@ -574,101 +574,100 @@ } }, "node_modules/@aws-sdk/client-ecs": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-ecs/-/client-ecs-3.888.0.tgz", - "integrity": "sha512-mj1yI5/eVkofd5kt1GtKukFG5QFlFMI4V+TgXJf62vAVCGCUTlJCUxLovfuORi5WPiN1d91Eco2NHG2qMv8fqA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-ecs/-/client-ecs-3.908.0.tgz", + "integrity": "sha512-HVgwoj/+VhM/7DWv7UgoKWP+AmtxCm1Tnc964+rCECzuSCcC3cYXOf0LZJLmaUxCQHLEzNuANsAMyl9jCzXenw==", "license": "Apache-2.0", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.888.0", - "@aws-sdk/credential-provider-node": "3.888.0", - "@aws-sdk/middleware-host-header": "3.887.0", - "@aws-sdk/middleware-logger": "3.887.0", - "@aws-sdk/middleware-recursion-detection": "3.887.0", - "@aws-sdk/middleware-user-agent": "3.888.0", - "@aws-sdk/region-config-resolver": "3.887.0", - "@aws-sdk/types": "3.887.0", - "@aws-sdk/util-endpoints": "3.887.0", - "@aws-sdk/util-user-agent-browser": "3.887.0", - "@aws-sdk/util-user-agent-node": "3.888.0", - "@smithy/config-resolver": "^4.2.1", - "@smithy/core": "^3.11.0", - "@smithy/fetch-http-handler": "^5.2.1", - "@smithy/hash-node": "^4.1.1", - "@smithy/invalid-dependency": "^4.1.1", - "@smithy/middleware-content-length": "^4.1.1", - "@smithy/middleware-endpoint": "^4.2.1", - "@smithy/middleware-retry": "^4.2.1", - "@smithy/middleware-serde": "^4.1.1", - "@smithy/middleware-stack": "^4.1.1", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/node-http-handler": "^4.2.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/smithy-client": "^4.6.1", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-body-length-browser": "^4.1.0", - "@smithy/util-body-length-node": "^4.1.0", - "@smithy/util-defaults-mode-browser": "^4.1.1", - "@smithy/util-defaults-mode-node": "^4.1.1", - "@smithy/util-endpoints": "^3.1.1", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-retry": "^4.1.1", - "@smithy/util-utf8": "^4.1.0", - "@smithy/util-waiter": "^4.1.1", - "@types/uuid": "^9.0.1", - "tslib": "^2.6.2", - "uuid": "^9.0.1" + "@aws-sdk/core": "3.908.0", + "@aws-sdk/credential-provider-node": "3.908.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.908.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.907.0", + "@aws-sdk/util-user-agent-node": "3.908.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.15.0", + "@smithy/fetch-http-handler": "^5.3.1", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.1", + "@smithy/middleware-retry": "^4.4.1", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.1", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.0", + "@smithy/util-defaults-mode-node": "^4.2.1", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "@smithy/util-waiter": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/client-sso": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.888.0.tgz", - "integrity": "sha512-8CLy/ehGKUmekjH+VtZJ4w40PqDg3u0K7uPziq/4P8Q7LLgsy8YQoHNbuY4am7JU3HWrqLXJI9aaz1+vPGPoWA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.908.0.tgz", + "integrity": "sha512-PseFMWvtac+Q+zaY9DMISE+2+glNh0ROJ1yR4gMzeafNHSwkdYu4qcgxLWIOnIodGydBv/tQ6nzHPzExXnUUgw==", "license": "Apache-2.0", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.888.0", - "@aws-sdk/middleware-host-header": "3.887.0", - "@aws-sdk/middleware-logger": "3.887.0", - "@aws-sdk/middleware-recursion-detection": "3.887.0", - "@aws-sdk/middleware-user-agent": "3.888.0", - "@aws-sdk/region-config-resolver": "3.887.0", - "@aws-sdk/types": "3.887.0", - "@aws-sdk/util-endpoints": "3.887.0", - "@aws-sdk/util-user-agent-browser": "3.887.0", - "@aws-sdk/util-user-agent-node": "3.888.0", - "@smithy/config-resolver": "^4.2.1", - "@smithy/core": "^3.11.0", - "@smithy/fetch-http-handler": "^5.2.1", - "@smithy/hash-node": "^4.1.1", - "@smithy/invalid-dependency": "^4.1.1", - "@smithy/middleware-content-length": "^4.1.1", - "@smithy/middleware-endpoint": "^4.2.1", - "@smithy/middleware-retry": "^4.2.1", - "@smithy/middleware-serde": "^4.1.1", - "@smithy/middleware-stack": "^4.1.1", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/node-http-handler": "^4.2.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/smithy-client": "^4.6.1", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-body-length-browser": "^4.1.0", - "@smithy/util-body-length-node": "^4.1.0", - "@smithy/util-defaults-mode-browser": "^4.1.1", - "@smithy/util-defaults-mode-node": "^4.1.1", - "@smithy/util-endpoints": "^3.1.1", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-retry": "^4.1.1", - "@smithy/util-utf8": "^4.1.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.908.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.907.0", + "@aws-sdk/util-user-agent-node": "3.908.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.15.0", + "@smithy/fetch-http-handler": "^5.3.1", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.1", + "@smithy/middleware-retry": "^4.4.1", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.1", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.0", + "@smithy/util-defaults-mode-node": "^4.2.1", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -676,25 +675,23 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/core": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.888.0.tgz", - "integrity": "sha512-L3S2FZywACo4lmWv37Y4TbefuPJ1fXWyWwIJ3J4wkPYFJ47mmtUPqThlVrSbdTHkEjnZgJe5cRfxk0qCLsFh1w==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.908.0.tgz", + "integrity": "sha512-okl6FC2cQT1Oidvmnmvyp/IEvqENBagKO0ww4YV5UtBkf0VlhAymCWkZqhovtklsqgq0otag2VRPAgnrMt6nVQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@aws-sdk/xml-builder": "3.887.0", - "@smithy/core": "^3.11.0", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/property-provider": "^4.0.5", - "@smithy/protocol-http": "^5.2.1", - "@smithy/signature-v4": "^5.1.3", - "@smithy/smithy-client": "^4.6.1", - "@smithy/types": "^4.5.0", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-body-length-browser": "^4.1.0", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-utf8": "^4.1.0", - "fast-xml-parser": "5.2.5", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/xml-builder": "3.901.0", + "@smithy/core": "^3.15.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/signature-v4": "^5.3.0", + "@smithy/smithy-client": "^4.7.1", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -702,15 +699,15 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-env": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.888.0.tgz", - "integrity": "sha512-shPi4AhUKbIk7LugJWvNpeZA8va7e5bOHAEKo89S0Ac8WDZt2OaNzbh/b9l0iSL2eEyte8UgIsYGcFxOwIF1VA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.908.0.tgz", + "integrity": "sha512-FK2YuxoI5CxUflPOIMbVAwDbi6Xvu+2sXopXLmrHc2PfI39M3vmjEoQwYCP8WuQSRb+TbAP3xAkxHjFSBFR35w==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -718,20 +715,20 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-http": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.888.0.tgz", - "integrity": "sha512-Jvuk6nul0lE7o5qlQutcqlySBHLXOyoPtiwE6zyKbGc7RVl0//h39Lab7zMeY2drMn8xAnIopL4606Fd8JI/Hw==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.908.0.tgz", + "integrity": "sha512-eLbz0geVW9EykujQNnYfR35Of8MreI6pau5K6XDFDUSWO9GF8wqH7CQwbXpXHBlCTHtq4QSLxzorD8U5CROhUw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/fetch-http-handler": "^5.2.1", - "@smithy/node-http-handler": "^4.2.1", - "@smithy/property-provider": "^4.0.5", - "@smithy/protocol-http": "^5.2.1", - "@smithy/smithy-client": "^4.6.1", - "@smithy/types": "^4.5.0", - "@smithy/util-stream": "^4.3.1", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/fetch-http-handler": "^5.3.1", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.1", + "@smithy/types": "^4.6.0", + "@smithy/util-stream": "^4.5.0", "tslib": "^2.6.2" }, "engines": { @@ -739,23 +736,23 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.888.0.tgz", - "integrity": "sha512-M82ItvS5yq+tO6ZOV1ruaVs2xOne+v8HW85GFCXnz8pecrzYdgxh6IsVqEbbWruryG/mUGkWMbkBZoEsy4MgyA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.908.0.tgz", + "integrity": "sha512-7Cgnv5wabgFtsgr+Uc/76EfPNGyxmbG8aICn3g3D3iJlcO4uuOZI8a77i0afoDdchZrTC6TG6UusS/NAW6zEoQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/credential-provider-env": "3.888.0", - "@aws-sdk/credential-provider-http": "3.888.0", - "@aws-sdk/credential-provider-process": "3.888.0", - "@aws-sdk/credential-provider-sso": "3.888.0", - "@aws-sdk/credential-provider-web-identity": "3.888.0", - "@aws-sdk/nested-clients": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/credential-provider-imds": "^4.0.7", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/credential-provider-env": "3.908.0", + "@aws-sdk/credential-provider-http": "3.908.0", + "@aws-sdk/credential-provider-process": "3.908.0", + "@aws-sdk/credential-provider-sso": "3.908.0", + "@aws-sdk/credential-provider-web-identity": "3.908.0", + "@aws-sdk/nested-clients": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -763,22 +760,22 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-node": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.888.0.tgz", - "integrity": "sha512-KCrQh1dCDC8Y+Ap3SZa6S81kHk+p+yAaOQ5jC3dak4zhHW3RCrsGR/jYdemTOgbEGcA6ye51UbhWfrrlMmeJSA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.908.0.tgz", + "integrity": "sha512-8OKbykpGw5bdfF/pLTf8YfUi1Kl8o1CTjBqWQTsLOkE3Ho3hsp1eQx8Cz4ttrpv0919kb+lox62DgmAOEmTr1w==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/credential-provider-env": "3.888.0", - "@aws-sdk/credential-provider-http": "3.888.0", - "@aws-sdk/credential-provider-ini": "3.888.0", - "@aws-sdk/credential-provider-process": "3.888.0", - "@aws-sdk/credential-provider-sso": "3.888.0", - "@aws-sdk/credential-provider-web-identity": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/credential-provider-imds": "^4.0.7", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/credential-provider-env": "3.908.0", + "@aws-sdk/credential-provider-http": "3.908.0", + "@aws-sdk/credential-provider-ini": "3.908.0", + "@aws-sdk/credential-provider-process": "3.908.0", + "@aws-sdk/credential-provider-sso": "3.908.0", + "@aws-sdk/credential-provider-web-identity": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -786,16 +783,16 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-process": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.888.0.tgz", - "integrity": "sha512-+aX6piSukPQ8DUS4JAH344GePg8/+Q1t0+kvSHAZHhYvtQ/1Zek3ySOJWH2TuzTPCafY4nmWLcQcqvU1w9+4Lw==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.908.0.tgz", + "integrity": "sha512-sWnbkGjDPBi6sODUzrAh5BCDpnPw0wpK8UC/hWI13Q8KGfyatAmCBfr+9OeO3+xBHa8N5AskMncr7C4qS846yQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -803,18 +800,18 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.888.0.tgz", - "integrity": "sha512-b1ZJji7LJ6E/j1PhFTyvp51in2iCOQ3VP6mj5H6f5OUnqn7efm41iNMoinKr87n0IKZw7qput5ggXVxEdPhouA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.908.0.tgz", + "integrity": "sha512-WV/aOzuS6ZZhrkPty6TJ3ZG24iS8NXP0m3GuTVuZ5tKi9Guss31/PJ1CrKPRCYGm15CsIjf+mrUxVnNYv9ap5g==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-sso": "3.888.0", - "@aws-sdk/core": "3.888.0", - "@aws-sdk/token-providers": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/client-sso": "3.908.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/token-providers": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -822,16 +819,17 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.888.0.tgz", - "integrity": "sha512-7P0QNtsDzMZdmBAaY/vY1BsZHwTGvEz3bsn2bm5VSKFAeMmZqsHK1QeYdNsFjLtegnVh+wodxMq50jqLv3LFlA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.908.0.tgz", + "integrity": "sha512-9xWrFn6nWlF5KlV4XYW+7E6F33S3wUUEGRZ/+pgDhkIZd527ycT2nPG2dZ3fWUZMlRmzijP20QIJDqEbbGWe1Q==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/nested-clients": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/nested-clients": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -839,14 +837,14 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/middleware-host-header": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.887.0.tgz", - "integrity": "sha512-ulzqXv6NNqdu/kr0sgBYupWmahISHY+azpJidtK6ZwQIC+vBUk9NdZeqQpy7KVhIk2xd4+5Oq9rxapPwPI21CA==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.901.0.tgz", + "integrity": "sha512-yWX7GvRmqBtbNnUW7qbre3GvZmyYwU0WHefpZzDTYDoNgatuYq6LgUIQ+z5C04/kCRoFkAFrHag8a3BXqFzq5A==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", + "@aws-sdk/types": "3.901.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -854,13 +852,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/middleware-logger": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.887.0.tgz", - "integrity": "sha512-YbbgLI6jKp2qSoAcHnXrQ5jcuc5EYAmGLVFgMVdk8dfCfJLfGGSaOLxF4CXC7QYhO50s+mPPkhBYejCik02Kug==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.901.0.tgz", + "integrity": "sha512-UoHebjE7el/tfRo8/CQTj91oNUm+5Heus5/a4ECdmWaSCHCS/hXTsU3PTTHAY67oAQR8wBLFPfp3mMvXjB+L2A==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@smithy/types": "^4.5.0", + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -868,15 +866,15 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.887.0.tgz", - "integrity": "sha512-tjrUXFtQnFLo+qwMveq5faxP5MQakoLArXtqieHphSqZTXm21wDJM73hgT4/PQQGTwgYjDKqnqsE1hvk0hcfDw==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.901.0.tgz", + "integrity": "sha512-Wd2t8qa/4OL0v/oDpCHHYkgsXJr8/ttCxrvCKAt0H1zZe2LlRhY9gpDVKqdertfHrHDj786fOvEQA28G1L75Dg==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", + "@aws-sdk/types": "3.901.0", "@aws/lambda-invoke-store": "^0.0.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -884,17 +882,17 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.888.0.tgz", - "integrity": "sha512-ZkcUkoys8AdrNNG7ATjqw2WiXqrhTvT+r4CIK3KhOqIGPHX0p0DQWzqjaIl7ZhSUToKoZ4Ud7MjF795yUr73oA==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.908.0.tgz", + "integrity": "sha512-R0ePEOku72EvyJWy/D0Z5f/Ifpfxa0U9gySO3stpNhOox87XhsILpcIsCHPy0OHz1a7cMoZsF6rMKSzDeCnogQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@aws-sdk/util-endpoints": "3.887.0", - "@smithy/core": "^3.11.0", - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@smithy/core": "^3.15.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -902,48 +900,48 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/nested-clients": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.888.0.tgz", - "integrity": "sha512-py4o4RPSGt+uwGvSBzR6S6cCBjS4oTX5F8hrHFHfPCdIOMVjyOBejn820jXkCrcdpSj3Qg1yUZXxsByvxc9Lyg==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.908.0.tgz", + "integrity": "sha512-ZxDYrfxOKXNFHLyvJtT96TJ0p4brZOhwRE4csRXrezEVUN+pNgxuem95YvMALPVhlVqON2CTzr8BX+CcBKvX9Q==", "license": "Apache-2.0", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.888.0", - "@aws-sdk/middleware-host-header": "3.887.0", - "@aws-sdk/middleware-logger": "3.887.0", - "@aws-sdk/middleware-recursion-detection": "3.887.0", - "@aws-sdk/middleware-user-agent": "3.888.0", - "@aws-sdk/region-config-resolver": "3.887.0", - "@aws-sdk/types": "3.887.0", - "@aws-sdk/util-endpoints": "3.887.0", - "@aws-sdk/util-user-agent-browser": "3.887.0", - "@aws-sdk/util-user-agent-node": "3.888.0", - "@smithy/config-resolver": "^4.2.1", - "@smithy/core": "^3.11.0", - "@smithy/fetch-http-handler": "^5.2.1", - "@smithy/hash-node": "^4.1.1", - "@smithy/invalid-dependency": "^4.1.1", - "@smithy/middleware-content-length": "^4.1.1", - "@smithy/middleware-endpoint": "^4.2.1", - "@smithy/middleware-retry": "^4.2.1", - "@smithy/middleware-serde": "^4.1.1", - "@smithy/middleware-stack": "^4.1.1", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/node-http-handler": "^4.2.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/smithy-client": "^4.6.1", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-body-length-browser": "^4.1.0", - "@smithy/util-body-length-node": "^4.1.0", - "@smithy/util-defaults-mode-browser": "^4.1.1", - "@smithy/util-defaults-mode-node": "^4.1.1", - "@smithy/util-endpoints": "^3.1.1", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-retry": "^4.1.1", - "@smithy/util-utf8": "^4.1.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.908.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.907.0", + "@aws-sdk/util-user-agent-node": "3.908.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.15.0", + "@smithy/fetch-http-handler": "^5.3.1", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.1", + "@smithy/middleware-retry": "^4.4.1", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.1", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.0", + "@smithy/util-defaults-mode-node": "^4.2.1", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -951,16 +949,16 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/region-config-resolver": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.887.0.tgz", - "integrity": "sha512-VdSMrIqJ3yjJb/fY+YAxrH/lCVv0iL8uA+lbMNfQGtO5tB3Zx6SU9LEpUwBNX8fPK1tUpI65CNE4w42+MY/7Mg==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.901.0.tgz", + "integrity": "sha512-7F0N888qVLHo4CSQOsnkZ4QAp8uHLKJ4v3u09Ly5k4AEStrSlFpckTPyUx6elwGL+fxGjNE2aakK8vEgzzCV0A==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/types": "^4.5.0", - "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.1.1", + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -968,17 +966,17 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/token-providers": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.888.0.tgz", - "integrity": "sha512-WA3NF+3W8GEuCMG1WvkDYbB4z10G3O8xuhT7QSjhvLYWQ9CPt3w4VpVIfdqmUn131TCIbhCzD0KN/1VJTjAjyw==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.908.0.tgz", + "integrity": "sha512-4SosHWRQ8hj1X2yDenCYHParcCjHcd7S+Mdb/lelwF0JBFCNC+dNCI9ws3cP/dFdZO/AIhJQGUBzEQtieloixw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.888.0", - "@aws-sdk/nested-clients": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.5.0", + "@aws-sdk/core": "3.908.0", + "@aws-sdk/nested-clients": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -986,12 +984,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/types": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.887.0.tgz", - "integrity": "sha512-fmTEJpUhsPsovQ12vZSpVTEP/IaRoJAMBGQXlQNjtCpkBp6Iq3KQDa/HDaPINE+3xxo6XvTdtibsNOd5zJLV9A==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.901.0.tgz", + "integrity": "sha512-FfEM25hLEs4LoXsLXQ/q6X6L4JmKkKkbVFpKD4mwfVHtRVQG6QxJiCPcrkcPISquiy6esbwK2eh64TWbiD60cg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -999,15 +997,15 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/util-endpoints": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.887.0.tgz", - "integrity": "sha512-kpegvT53KT33BMeIcGLPA65CQVxLUL/C3gTz9AzlU/SDmeusBHX4nRApAicNzI/ltQ5lxZXbQn18UczzBuwF1w==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.901.0.tgz", + "integrity": "sha512-5nZP3hGA8FHEtKvEQf4Aww5QZOkjLW1Z+NixSd+0XKfHvA39Ah5sZboScjLx0C9kti/K3OGW1RCx5K9Zc3bZqg==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", - "@smithy/util-endpoints": "^3.1.1", + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", "tslib": "^2.6.2" }, "engines": { @@ -1015,27 +1013,27 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.887.0.tgz", - "integrity": "sha512-X71UmVsYc6ZTH4KU6hA5urOzYowSXc3qvroagJNLJYU1ilgZ529lP4J9XOYfEvTXkLR1hPFSRxa43SrwgelMjA==", + "version": "3.907.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.907.0.tgz", + "integrity": "sha512-Hus/2YCQmtCEfr4Ls88d07Q99Ex59uvtktiPTV963Q7w7LHuIT/JBjrbwNxtSm2KlJR9PHNdqxwN+fSuNsMGMQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.887.0", - "@smithy/types": "^4.5.0", + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.888.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.888.0.tgz", - "integrity": "sha512-rSB3OHyuKXotIGfYEo//9sU0lXAUrTY28SUUnxzOGYuQsAt0XR5iYwBAp+RjV6x8f+Hmtbg0PdCsy1iNAXa0UQ==", + "version": "3.908.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.908.0.tgz", + "integrity": "sha512-l6AEaKUAYarcEy8T8NZ+dNZ00VGLs3fW2Cqu1AuPENaSad0/ahEU+VU7MpXS8FhMRGPgplxKVgCTLyTY0Lbssw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.888.0", - "@aws-sdk/types": "3.887.0", - "@smithy/node-config-provider": "^4.2.1", - "@smithy/types": "^4.5.0", + "@aws-sdk/middleware-user-agent": "3.908.0", + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", "tslib": "^2.6.2" }, "engines": { @@ -1051,12 +1049,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@aws-sdk/xml-builder": { - "version": "3.887.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.887.0.tgz", - "integrity": "sha512-lMwgWK1kNgUhHGfBvO/5uLe7TKhycwOn3eRCqsKPT9aPCx/HWuTlpcQp8oW2pCRGLS7qzcxqpQulcD+bbUL7XQ==", + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.901.0.tgz", + "integrity": "sha512-pxFCkuAP7Q94wMTNPAwi6hEtNrp/BdFf+HOrIEeFQsk4EoOmpKY3I6S+u6A9Wg295J80Kh74LqDWM22ux3z6Aw==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.6.0", + "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" }, "engines": { @@ -1064,12 +1063,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/abort-controller": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.1.1.tgz", - "integrity": "sha512-vkzula+IwRvPR6oKQhMYioM3A/oX/lFCZiwuxkQbRhqJS2S4YRY2k7k/SyR2jMf3607HLtbEwlRxi0ndXHMjRg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.1.tgz", + "integrity": "sha512-OvVe992TXYHR7QpYebmtw+/MF5AP9vU0fjfyfW1VmNYeA/dfibLhN13xrzIj+EO0HYMPur5lUIB9hRZ7IhjLDQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1077,37 +1076,36 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/core": { - "version": "3.11.0", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.11.0.tgz", - "integrity": "sha512-Abs5rdP1o8/OINtE49wwNeWuynCu0kme1r4RI3VXVrHr4odVDG7h7mTnw1WXXfN5Il+c25QOnrdL2y56USfxkA==", + "version": "3.16.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.16.0.tgz", + "integrity": "sha512-T6eJ+yhnCP5plm6aEaenUpxkHTd5zVCKpyWAbP4ekJ7R5wSmKQjmvQIA58CXB1sgrwaYZJXOJMeRtpghxP7n1g==", "license": "Apache-2.0", "dependencies": { - "@smithy/middleware-serde": "^4.1.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-body-length-browser": "^4.1.0", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-stream": "^4.3.1", - "@smithy/util-utf8": "^4.1.0", - "@types/uuid": "^9.0.1", - "tslib": "^2.6.2", - "uuid": "^9.0.1" + "@smithy/middleware-serde": "^4.2.1", + "@smithy/protocol-http": "^5.3.1", + "@smithy/types": "^4.7.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-middleware": "^4.2.1", + "@smithy/util-stream": "^4.5.1", + "@smithy/util-utf8": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/fetch-http-handler": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.2.1.tgz", - "integrity": "sha512-5/3wxKNtV3wO/hk1is+CZUhL8a1yy/U+9u9LKQ9kZTkMsHaQjJhc3stFfiujtMnkITjzWfndGA2f7g9Uh9vKng==", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.3.2.tgz", + "integrity": "sha512-3CXDhyjl6nz0na+te37f+aGqmDwJeyeo9GK7ThPStoa/ruZcUm17UPRC4xJvbm8Z4JCvbnh54mRCFtiR/IzXjw==", "license": "Apache-2.0", "dependencies": { - "@smithy/protocol-http": "^5.2.1", - "@smithy/querystring-builder": "^4.1.1", - "@smithy/types": "^4.5.0", - "@smithy/util-base64": "^4.1.0", + "@smithy/protocol-http": "^5.3.1", + "@smithy/querystring-builder": "^4.2.1", + "@smithy/types": "^4.7.0", + "@smithy/util-base64": "^4.3.0", "tslib": "^2.6.2" }, "engines": { @@ -1115,9 +1113,9 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/is-array-buffer": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.1.0.tgz", - "integrity": "sha512-ePTYUOV54wMogio+he4pBybe8fwg4sDvEVDBU8ZlHOZXbXK3/C0XfJgUCu6qAZcawv05ZhZzODGUerFBPsPUDQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -1127,18 +1125,18 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/middleware-endpoint": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.2.2.tgz", - "integrity": "sha512-M51KcwD+UeSOFtpALGf5OijWt915aQT5eJhqnMKJt7ZTfDfNcvg2UZgIgTZUoiORawb6o5lk4n3rv7vnzQXgsA==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.3.2.tgz", + "integrity": "sha512-3UP7E5SD0rF6cQEWVMxfbMvpC0fv9fTbusMQfKAXlff5g7L2tn2kspiiGX+nqyK78FV2kP/O2WS7rbIvhfw6/Q==", "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.11.0", - "@smithy/middleware-serde": "^4.1.1", - "@smithy/node-config-provider": "^4.2.2", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", - "@smithy/util-middleware": "^4.1.1", + "@smithy/core": "^3.16.0", + "@smithy/middleware-serde": "^4.2.1", + "@smithy/node-config-provider": "^4.3.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", + "@smithy/url-parser": "^4.2.1", + "@smithy/util-middleware": "^4.2.1", "tslib": "^2.6.2" }, "engines": { @@ -1146,13 +1144,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/middleware-serde": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.1.1.tgz", - "integrity": "sha512-lh48uQdbCoj619kRouev5XbWhCwRKLmphAif16c4J6JgJ4uXjub1PI6RL38d3BLliUvSso6klyB/LTNpWSNIyg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.2.1.tgz", + "integrity": "sha512-0J1EDeGGBNz0h0R/UGKudF7gBMS+UMJEWuNPY1hDV/RTyyKgBfsKH87nKCeCSB81EgjnBDFsnfXD2ZMRCfIPWA==", "license": "Apache-2.0", "dependencies": { - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", + "@smithy/protocol-http": "^5.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1160,12 +1158,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/middleware-stack": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.1.1.tgz", - "integrity": "sha512-ygRnniqNcDhHzs6QAPIdia26M7e7z9gpkIMUe/pK0RsrQ7i5MblwxY8078/QCnGq6AmlUUWgljK2HlelsKIb/A==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.2.1.tgz", + "integrity": "sha512-gWKgBqYYrcdtkEMzN8hEtypab7zgU4VVZHSwURAR5YGrvGJxbBh5mC9RPmVWS7TZxr/vB4yMKfxEQTrYRKRQ3Q==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1173,14 +1171,14 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1188,15 +1186,15 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/node-http-handler": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.2.1.tgz", - "integrity": "sha512-REyybygHlxo3TJICPF89N2pMQSf+p+tBJqpVe1+77Cfi9HBPReNjTgtZ1Vg73exq24vkqJskKDpfF74reXjxfw==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.4.0.tgz", + "integrity": "sha512-E00fuesARqnmdc1vR4qurQjQH+QWcsKjmM6kYoJBWjxgqNfp1WHc1SwfC18EdVaYamgctxyXV6kWhHmanhYgCg==", "license": "Apache-2.0", "dependencies": { - "@smithy/abort-controller": "^4.1.1", - "@smithy/protocol-http": "^5.2.1", - "@smithy/querystring-builder": "^4.1.1", - "@smithy/types": "^4.5.0", + "@smithy/abort-controller": "^4.2.1", + "@smithy/protocol-http": "^5.3.1", + "@smithy/querystring-builder": "^4.2.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1204,12 +1202,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1217,12 +1215,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/protocol-http": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.2.1.tgz", - "integrity": "sha512-T8SlkLYCwfT/6m33SIU/JOVGNwoelkrvGjFKDSDtVvAXj/9gOT78JVJEas5a+ETjOu4SVvpCstKgd0PxSu/aHw==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.1.tgz", + "integrity": "sha512-DqbfSgeZC0qo3/3fLgr5UEdOE7/o/VlVOt6LtpShwVcw3PIoqQMRCUTzMpJ0keAVb86Cl1w5YtW7uDUzeNMMLA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1230,13 +1228,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/querystring-builder": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.1.1.tgz", - "integrity": "sha512-J9b55bfimP4z/Jg1gNo+AT84hr90p716/nvxDkPGCD4W70MPms0h8KF50RDRgBGZeL83/u59DWNqJv6tEP/DHA==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.2.1.tgz", + "integrity": "sha512-2Qf5x7Afn6ofV3XLYL9+oaOwWK2FUC/LLTarex0SaXEKctVdzCdOOzEfaAZJSwSSiYqFWF6e2r0m7PFDzA44fA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", - "@smithy/util-uri-escape": "^4.1.0", + "@smithy/types": "^4.7.0", + "@smithy/util-uri-escape": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -1244,12 +1242,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/querystring-parser": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.1.1.tgz", - "integrity": "sha512-63TEp92YFz0oQ7Pj9IuI3IgnprP92LrZtRAkE3c6wLWJxfy/yOPRt39IOKerVr0JS770olzl0kGafXlAXZ1vng==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.1.tgz", + "integrity": "sha512-y1DmifEgOF5J1MmrLP2arzI17tEaVqD+NUnfE+sVcpPcEHmAUL0TF9gQzAi5s6GGHUyDurO+zHvZQOeo7LuJnQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1257,12 +1255,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1270,9 +1268,9 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -1282,13 +1280,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/url-parser": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.1.1.tgz", - "integrity": "sha512-bx32FUpkhcaKlEoOMbScvc93isaSiRM75pQ5IgIBaMkT7qMlIibpPRONyx/0CvrXHzJLpOn/u6YiDX2hcvs7Dg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.1.tgz", + "integrity": "sha512-dHm6hDcl79Ededl0oKgpSq3mM5b7Xdw+jic8bq1G7Z2spVpm7HpHJuLCV9PUJLjMbDbZfRUf5GEOnnOIvgfYgQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/querystring-parser": "^4.1.1", - "@smithy/types": "^4.5.0", + "@smithy/querystring-parser": "^4.2.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1296,13 +1294,13 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-base64": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.1.0.tgz", - "integrity": "sha512-RUGd4wNb8GeW7xk+AY5ghGnIwM96V0l2uzvs/uVHf+tIuVX2WSvynk5CxNoBCsM2rQRSZElAo9rt3G5mJ/gktQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz", + "integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/util-buffer-from": "^4.1.0", - "@smithy/util-utf8": "^4.1.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -1310,9 +1308,9 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-body-length-browser": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.1.0.tgz", - "integrity": "sha512-V2E2Iez+bo6bUMOTENPr6eEmepdY8Hbs+Uc1vkDKgKNA/brTJqOW/ai3JO1BGj9GbCeLqw90pbbH7HFQyFotGQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.2.0.tgz", + "integrity": "sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -1322,12 +1320,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-buffer-from": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.1.0.tgz", - "integrity": "sha512-N6yXcjfe/E+xKEccWEKzK6M+crMrlwaCepKja0pNnlSkm6SjAeLKKA++er5Ba0I17gvKfN/ThV+ZOx/CntKTVw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", "license": "Apache-2.0", "dependencies": { - "@smithy/is-array-buffer": "^4.1.0", + "@smithy/is-array-buffer": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -1335,9 +1333,9 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-hex-encoding": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.1.0.tgz", - "integrity": "sha512-1LcueNN5GYC4tr8mo14yVYbh/Ur8jHhWOxniZXii+1+ePiIbsLZ5fEI0QQGtbRRP5mOhmooos+rLmVASGGoq5w==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz", + "integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -1347,12 +1345,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-middleware": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.1.1.tgz", - "integrity": "sha512-CGmZ72mL29VMfESz7S6dekqzCh8ZISj3B+w0g1hZFXaOjGTVaSqfAEFAq8EGp8fUL+Q2l8aqNmt8U1tglTikeg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.1.tgz", + "integrity": "sha512-4rf5Ma0e0uuKmtzMihsvs3jnb9iGMRDWrUe6mfdZBWm52PW1xVHdEeP4+swhheF+YAXhVH/O+taKJuqOrVsG3w==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -1360,18 +1358,18 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-stream": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.3.1.tgz", - "integrity": "sha512-khKkW/Jqkgh6caxMWbMuox9+YfGlsk9OnHOYCGVEdYQb/XVzcORXHLYUubHmmda0pubEDncofUrPNniS9d+uAA==", + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.5.1.tgz", + "integrity": "sha512-kVnOiYDDb84ZUGwpQBiVQROWR7epNXikxMGw971Mww3+eufKl2NHYyao2Gg4Wd3iG+D9hF/d9VrmMBxBcVprXw==", "license": "Apache-2.0", "dependencies": { - "@smithy/fetch-http-handler": "^5.2.1", - "@smithy/node-http-handler": "^4.2.1", - "@smithy/types": "^4.5.0", - "@smithy/util-base64": "^4.1.0", - "@smithy/util-buffer-from": "^4.1.0", - "@smithy/util-hex-encoding": "^4.1.0", - "@smithy/util-utf8": "^4.1.0", + "@smithy/fetch-http-handler": "^5.3.2", + "@smithy/node-http-handler": "^4.4.0", + "@smithy/types": "^4.7.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -1379,9 +1377,9 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-uri-escape": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.1.0.tgz", - "integrity": "sha512-b0EFQkq35K5NHUYxU72JuoheM6+pytEVUGlTwiFxWFpmddA+Bpz3LgsPRIpBk8lnPE47yT7AF2Egc3jVnKLuPg==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.0.tgz", + "integrity": "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -1391,12 +1389,12 @@ } }, "node_modules/@aws-sdk/client-ecs/node_modules/@smithy/util-utf8": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.1.0.tgz", - "integrity": "sha512-mEu1/UIXAdNYuBcyEPbjScKi/+MQVXNIuY/7Cm5XLIWe319kDrT5SizBE95jqtmEXoDbGoZxKLCMttdZdqTZKQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", "license": "Apache-2.0", "dependencies": { - "@smithy/util-buffer-from": "^4.1.0", + "@smithy/util-buffer-from": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4952,15 +4950,15 @@ } }, "node_modules/@smithy/config-resolver": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.2.2.tgz", - "integrity": "sha512-IT6MatgBWagLybZl1xQcURXRICvqz1z3APSCAI9IqdvfCkrA7RaQIEfgC6G/KvfxnDfQUDqFV+ZlixcuFznGBQ==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.3.1.tgz", + "integrity": "sha512-tWDwrWy37CDVGeaP8AIGZPFL2RoFtmd5Y+nTzLw5qroXNedT2S66EY2d+XzB1zxulCd6nfDXnAQu4auq90aj5Q==", "license": "Apache-2.0", "dependencies": { - "@smithy/node-config-provider": "^4.2.2", - "@smithy/types": "^4.5.0", - "@smithy/util-config-provider": "^4.1.0", - "@smithy/util-middleware": "^4.1.1", + "@smithy/node-config-provider": "^4.3.1", + "@smithy/types": "^4.7.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.1", "tslib": "^2.6.2" }, "engines": { @@ -4968,14 +4966,14 @@ } }, "node_modules/@smithy/config-resolver/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -4983,12 +4981,12 @@ } }, "node_modules/@smithy/config-resolver/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -4996,12 +4994,12 @@ } }, "node_modules/@smithy/config-resolver/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5009,9 +5007,9 @@ } }, "node_modules/@smithy/config-resolver/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5021,12 +5019,12 @@ } }, "node_modules/@smithy/config-resolver/node_modules/@smithy/util-middleware": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.1.1.tgz", - "integrity": "sha512-CGmZ72mL29VMfESz7S6dekqzCh8ZISj3B+w0g1hZFXaOjGTVaSqfAEFAq8EGp8fUL+Q2l8aqNmt8U1tglTikeg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.1.tgz", + "integrity": "sha512-4rf5Ma0e0uuKmtzMihsvs3jnb9iGMRDWrUe6mfdZBWm52PW1xVHdEeP4+swhheF+YAXhVH/O+taKJuqOrVsG3w==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5052,15 +5050,15 @@ } }, "node_modules/@smithy/credential-provider-imds": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.1.2.tgz", - "integrity": "sha512-JlYNq8TShnqCLg0h+afqe2wLAwZpuoSgOyzhYvTgbiKBWRov+uUve+vrZEQO6lkdLOWPh7gK5dtb9dS+KGendg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.2.1.tgz", + "integrity": "sha512-Y7Gq6xZvAUJOf60prfpknyKIJoIU89q/t6Cr4AWLYZBaaIhEdWJRIWvLqiqL5Hb6iK8btorKHI8jT6ZuQB+BVg==", "license": "Apache-2.0", "dependencies": { - "@smithy/node-config-provider": "^4.2.2", - "@smithy/property-provider": "^4.1.1", - "@smithy/types": "^4.5.0", - "@smithy/url-parser": "^4.1.1", + "@smithy/node-config-provider": "^4.3.1", + "@smithy/property-provider": "^4.2.1", + "@smithy/types": "^4.7.0", + "@smithy/url-parser": "^4.2.1", "tslib": "^2.6.2" }, "engines": { @@ -5068,14 +5066,14 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5083,12 +5081,12 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5096,12 +5094,12 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/querystring-parser": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.1.1.tgz", - "integrity": "sha512-63TEp92YFz0oQ7Pj9IuI3IgnprP92LrZtRAkE3c6wLWJxfy/yOPRt39IOKerVr0JS770olzl0kGafXlAXZ1vng==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.1.tgz", + "integrity": "sha512-y1DmifEgOF5J1MmrLP2arzI17tEaVqD+NUnfE+sVcpPcEHmAUL0TF9gQzAi5s6GGHUyDurO+zHvZQOeo7LuJnQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5109,12 +5107,12 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5122,9 +5120,9 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5134,13 +5132,13 @@ } }, "node_modules/@smithy/credential-provider-imds/node_modules/@smithy/url-parser": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.1.1.tgz", - "integrity": "sha512-bx32FUpkhcaKlEoOMbScvc93isaSiRM75pQ5IgIBaMkT7qMlIibpPRONyx/0CvrXHzJLpOn/u6YiDX2hcvs7Dg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.1.tgz", + "integrity": "sha512-dHm6hDcl79Ededl0oKgpSq3mM5b7Xdw+jic8bq1G7Z2spVpm7HpHJuLCV9PUJLjMbDbZfRUf5GEOnnOIvgfYgQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/querystring-parser": "^4.1.1", - "@smithy/types": "^4.5.0", + "@smithy/querystring-parser": "^4.2.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5160,14 +5158,14 @@ } }, "node_modules/@smithy/hash-node": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.1.1.tgz", - "integrity": "sha512-H9DIU9WBLhYrvPs9v4sYvnZ1PiAI0oc8CgNQUJ1rpN3pP7QADbTOUjchI2FB764Ub0DstH5xbTqcMJu1pnVqxA==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.2.1.tgz", + "integrity": "sha512-eqyR+zua9LI8K0NhYMUEh8HDy7zaT1gRuB3d1kNIKeSG9nc2JxNbKXYNRdmIvAWG3wJyl9uUWPs+H3k8uDes1Q==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", - "@smithy/util-buffer-from": "^4.1.0", - "@smithy/util-utf8": "^4.1.0", + "@smithy/types": "^4.7.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5175,9 +5173,9 @@ } }, "node_modules/@smithy/hash-node/node_modules/@smithy/is-array-buffer": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.1.0.tgz", - "integrity": "sha512-ePTYUOV54wMogio+he4pBybe8fwg4sDvEVDBU8ZlHOZXbXK3/C0XfJgUCu6qAZcawv05ZhZzODGUerFBPsPUDQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5187,9 +5185,9 @@ } }, "node_modules/@smithy/hash-node/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5199,12 +5197,12 @@ } }, "node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.1.0.tgz", - "integrity": "sha512-N6yXcjfe/E+xKEccWEKzK6M+crMrlwaCepKja0pNnlSkm6SjAeLKKA++er5Ba0I17gvKfN/ThV+ZOx/CntKTVw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", "license": "Apache-2.0", "dependencies": { - "@smithy/is-array-buffer": "^4.1.0", + "@smithy/is-array-buffer": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5212,12 +5210,12 @@ } }, "node_modules/@smithy/hash-node/node_modules/@smithy/util-utf8": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.1.0.tgz", - "integrity": "sha512-mEu1/UIXAdNYuBcyEPbjScKi/+MQVXNIuY/7Cm5XLIWe319kDrT5SizBE95jqtmEXoDbGoZxKLCMttdZdqTZKQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", "license": "Apache-2.0", "dependencies": { - "@smithy/util-buffer-from": "^4.1.0", + "@smithy/util-buffer-from": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5225,12 +5223,12 @@ } }, "node_modules/@smithy/invalid-dependency": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.1.1.tgz", - "integrity": "sha512-1AqLyFlfrrDkyES8uhINRlJXmHA2FkG+3DY8X+rmLSqmFwk3DJnvhyGzyByPyewh2jbmV+TYQBEfngQax8IFGg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.2.1.tgz", + "integrity": "sha512-mGH4fyQwVun9jtAbNQjU5Dt2pItOM1ULQrceaISyyu8pEjreBjyC0T5BN+zU2ltqKF3NefjQ+ApfoAk1w1UplQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5238,9 +5236,9 @@ } }, "node_modules/@smithy/invalid-dependency/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5261,13 +5259,13 @@ } }, "node_modules/@smithy/middleware-content-length": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.1.1.tgz", - "integrity": "sha512-9wlfBBgTsRvC2JxLJxv4xDGNBrZuio3AgSl0lSFX7fneW2cGskXTYpFxCdRYD2+5yzmsiTuaAJD1Wp7gWt9y9w==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.2.1.tgz", + "integrity": "sha512-+V6TdTAcS/dGILfe4hZP5lVnCuUvcX05yj+GihbOpy/ylGzUYhE/oYmv4vU33vMj5rfpdcfuyuESHkJTTRDXGw==", "license": "Apache-2.0", "dependencies": { - "@smithy/protocol-http": "^5.2.1", - "@smithy/types": "^4.5.0", + "@smithy/protocol-http": "^5.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5275,12 +5273,12 @@ } }, "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.2.1.tgz", - "integrity": "sha512-T8SlkLYCwfT/6m33SIU/JOVGNwoelkrvGjFKDSDtVvAXj/9gOT78JVJEas5a+ETjOu4SVvpCstKgd0PxSu/aHw==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.1.tgz", + "integrity": "sha512-DqbfSgeZC0qo3/3fLgr5UEdOE7/o/VlVOt6LtpShwVcw3PIoqQMRCUTzMpJ0keAVb86Cl1w5YtW7uDUzeNMMLA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5288,9 +5286,9 @@ } }, "node_modules/@smithy/middleware-content-length/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5318,35 +5316,34 @@ } }, "node_modules/@smithy/middleware-retry": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.2.2.tgz", - "integrity": "sha512-KZJueEOO+PWqflv2oGx9jICpHdBYXwCI19j7e2V3IMwKgFcXc9D9q/dsTf4B+uCnYxjNoS1jpyv6pGNGRsKOXA==", + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.4.2.tgz", + "integrity": "sha512-cuPmDJi7AE7PkdfeqJaHKBR33mXCl1MPxrboQDR/zZUo9u947m0gnYRd25NTSRER5LZpNDCvVTSedeAC9dHckA==", "license": "Apache-2.0", "dependencies": { - "@smithy/node-config-provider": "^4.2.2", - "@smithy/protocol-http": "^5.2.1", - "@smithy/service-error-classification": "^4.1.1", - "@smithy/smithy-client": "^4.6.2", - "@smithy/types": "^4.5.0", - "@smithy/util-middleware": "^4.1.1", - "@smithy/util-retry": "^4.1.1", - "@types/uuid": "^9.0.1", - "tslib": "^2.6.2", - "uuid": "^9.0.1" + "@smithy/node-config-provider": "^4.3.1", + "@smithy/protocol-http": "^5.3.1", + "@smithy/service-error-classification": "^4.2.1", + "@smithy/smithy-client": "^4.8.0", + "@smithy/types": "^4.7.0", + "@smithy/util-middleware": "^4.2.1", + "@smithy/util-retry": "^4.2.1", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5354,12 +5351,12 @@ } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5367,12 +5364,12 @@ } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.2.1.tgz", - "integrity": "sha512-T8SlkLYCwfT/6m33SIU/JOVGNwoelkrvGjFKDSDtVvAXj/9gOT78JVJEas5a+ETjOu4SVvpCstKgd0PxSu/aHw==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.1.tgz", + "integrity": "sha512-DqbfSgeZC0qo3/3fLgr5UEdOE7/o/VlVOt6LtpShwVcw3PIoqQMRCUTzMpJ0keAVb86Cl1w5YtW7uDUzeNMMLA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5380,12 +5377,12 @@ } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5393,9 +5390,9 @@ } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5405,12 +5402,12 @@ } }, "node_modules/@smithy/middleware-retry/node_modules/@smithy/util-middleware": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.1.1.tgz", - "integrity": "sha512-CGmZ72mL29VMfESz7S6dekqzCh8ZISj3B+w0g1hZFXaOjGTVaSqfAEFAq8EGp8fUL+Q2l8aqNmt8U1tglTikeg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.1.tgz", + "integrity": "sha512-4rf5Ma0e0uuKmtzMihsvs3jnb9iGMRDWrUe6mfdZBWm52PW1xVHdEeP4+swhheF+YAXhVH/O+taKJuqOrVsG3w==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5520,21 +5517,21 @@ } }, "node_modules/@smithy/service-error-classification": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.1.1.tgz", - "integrity": "sha512-Iam75b/JNXyDE41UvrlM6n8DNOa/r1ylFyvgruTUx7h2Uk7vDNV9AAwP1vfL1fOL8ls0xArwEGVcGZVd7IO/Cw==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.2.1.tgz", + "integrity": "sha512-NEcg3bGL9MddDd0GtH1+6bLg+e9SpbNEAVV8vEM4uWgqixECItz6wf0sYcq+N0lQjeRljdwaG3wxd2YgJ7JfbQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0" + "@smithy/types": "^4.7.0" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/service-error-classification/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5556,18 +5553,18 @@ } }, "node_modules/@smithy/signature-v4": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.2.0.tgz", - "integrity": "sha512-ObX1ZqG2DdZQlXx9mLD7yAR8AGb7yXurGm+iWx9x4l1fBZ8CZN2BRT09aSbcXVPZXWGdn5VtMuupjxhOTI2EjA==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.3.1.tgz", + "integrity": "sha512-7jimpk6X2jzV3UmesOFFV675N/4D8QqNg6NdZFNa/RmWAco+jyX/TbX2mHFImNm+DoafpwEfcDNsPxDSYF0Pxw==", "license": "Apache-2.0", "dependencies": { - "@smithy/is-array-buffer": "^4.1.0", - "@smithy/protocol-http": "^5.2.0", - "@smithy/types": "^4.4.0", - "@smithy/util-hex-encoding": "^4.1.0", - "@smithy/util-middleware": "^4.1.0", - "@smithy/util-uri-escape": "^4.1.0", - "@smithy/util-utf8": "^4.1.0", + "@smithy/is-array-buffer": "^4.2.0", + "@smithy/protocol-http": "^5.3.1", + "@smithy/types": "^4.7.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-middleware": "^4.2.1", + "@smithy/util-uri-escape": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5575,9 +5572,9 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.1.0.tgz", - "integrity": "sha512-ePTYUOV54wMogio+he4pBybe8fwg4sDvEVDBU8ZlHOZXbXK3/C0XfJgUCu6qAZcawv05ZhZzODGUerFBPsPUDQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5587,12 +5584,12 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/protocol-http": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.2.0.tgz", - "integrity": "sha512-bwjlh5JwdOQnA01be+5UvHK4HQz4iaRKlVG46hHSJuqi0Ribt3K06Z1oQ29i35Np4G9MCDgkOGcHVyLMreMcbg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.1.tgz", + "integrity": "sha512-DqbfSgeZC0qo3/3fLgr5UEdOE7/o/VlVOt6LtpShwVcw3PIoqQMRCUTzMpJ0keAVb86Cl1w5YtW7uDUzeNMMLA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.4.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5600,9 +5597,9 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/types": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.4.0.tgz", - "integrity": "sha512-4jY91NgZz+ZnSFcVzWwngOW6VuK3gR/ihTwSU1R/0NENe9Jd8SfWgbhDCAGUWL3bI7DiDSW7XF6Ui6bBBjrqXw==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5612,12 +5609,12 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/util-buffer-from": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.1.0.tgz", - "integrity": "sha512-N6yXcjfe/E+xKEccWEKzK6M+crMrlwaCepKja0pNnlSkm6SjAeLKKA++er5Ba0I17gvKfN/ThV+ZOx/CntKTVw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", "license": "Apache-2.0", "dependencies": { - "@smithy/is-array-buffer": "^4.1.0", + "@smithy/is-array-buffer": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5625,9 +5622,9 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.1.0.tgz", - "integrity": "sha512-1LcueNN5GYC4tr8mo14yVYbh/Ur8jHhWOxniZXii+1+ePiIbsLZ5fEI0QQGtbRRP5mOhmooos+rLmVASGGoq5w==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz", + "integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5637,12 +5634,12 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.1.0.tgz", - "integrity": "sha512-612onNcKyxhP7/YOTKFTb2F6sPYtMRddlT5mZvYf1zduzaGzkYhpYIPxIeeEwBZFjnvEqe53Ijl2cYEfJ9d6/Q==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.1.tgz", + "integrity": "sha512-4rf5Ma0e0uuKmtzMihsvs3jnb9iGMRDWrUe6mfdZBWm52PW1xVHdEeP4+swhheF+YAXhVH/O+taKJuqOrVsG3w==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.4.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5650,9 +5647,9 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.1.0.tgz", - "integrity": "sha512-b0EFQkq35K5NHUYxU72JuoheM6+pytEVUGlTwiFxWFpmddA+Bpz3LgsPRIpBk8lnPE47yT7AF2Egc3jVnKLuPg==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.0.tgz", + "integrity": "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5662,12 +5659,12 @@ } }, "node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.1.0.tgz", - "integrity": "sha512-mEu1/UIXAdNYuBcyEPbjScKi/+MQVXNIuY/7Cm5XLIWe319kDrT5SizBE95jqtmEXoDbGoZxKLCMttdZdqTZKQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", "license": "Apache-2.0", "dependencies": { - "@smithy/util-buffer-from": "^4.1.0", + "@smithy/util-buffer-from": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5733,9 +5730,9 @@ } }, "node_modules/@smithy/util-body-length-node": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.1.0.tgz", - "integrity": "sha512-BOI5dYjheZdgR9XiEM3HJcEMCXSoqbzu7CzIgYrx0UtmvtC3tC2iDGpJLsSRFffUpy8ymsg2ARMP5fR8mtuUQQ==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.2.1.tgz", + "integrity": "sha512-h53dz/pISVrVrfxV1iqXlx5pRg3V2YWFcSQyPyXZRrZoZj4R4DeWRDo1a7dd3CPTcFi3kE+98tuNyD2axyZReA==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5757,9 +5754,9 @@ } }, "node_modules/@smithy/util-config-provider": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.1.0.tgz", - "integrity": "sha512-swXz2vMjrP1ZusZWVTB/ai5gK+J8U0BWvP10v9fpcFvg+Xi/87LHvHfst2IgCs1i0v4qFZfGwCmeD/KNCdJZbQ==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.2.0.tgz", + "integrity": "sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5769,15 +5766,14 @@ } }, "node_modules/@smithy/util-defaults-mode-browser": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.1.2.tgz", - "integrity": "sha512-QKrOw01DvNHKgY+3p4r9Ut4u6EHLVZ01u6SkOMe6V6v5C+nRPXJeWh72qCT1HgwU3O7sxAIu23nNh+FOpYVZKA==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.3.1.tgz", + "integrity": "sha512-B3kaaqtc11rIc7SN3g6TYGdUrQfCkoHvpqbhd9kdfRUQZG7M7dcc0oLcCjMuBhCSUdtorkK7OA5uGq9BB+isaA==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/smithy-client": "^4.6.2", - "@smithy/types": "^4.5.0", - "bowser": "^2.11.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/smithy-client": "^4.8.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5785,12 +5781,12 @@ } }, "node_modules/@smithy/util-defaults-mode-browser/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5798,9 +5794,9 @@ } }, "node_modules/@smithy/util-defaults-mode-browser/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5810,17 +5806,17 @@ } }, "node_modules/@smithy/util-defaults-mode-node": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.1.2.tgz", - "integrity": "sha512-l2yRmSfx5haYHswPxMmCR6jGwgPs5LjHLuBwlj9U7nNBMS43YV/eevj+Xq1869UYdiynnMrCKtoOYQcwtb6lKg==", + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.2.2.tgz", + "integrity": "sha512-cneOHBPi/DGbjz65oV8wID+uUbtzrFAQ8w3a7uS3C1jjrInSrinAitup8SouDpmi8jr5GVOAck1/hsR3n/WvaQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/config-resolver": "^4.2.2", - "@smithy/credential-provider-imds": "^4.1.2", - "@smithy/node-config-provider": "^4.2.2", - "@smithy/property-provider": "^4.1.1", - "@smithy/smithy-client": "^4.6.2", - "@smithy/types": "^4.5.0", + "@smithy/config-resolver": "^4.3.1", + "@smithy/credential-provider-imds": "^4.2.1", + "@smithy/node-config-provider": "^4.3.1", + "@smithy/property-provider": "^4.2.1", + "@smithy/smithy-client": "^4.8.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5828,14 +5824,14 @@ } }, "node_modules/@smithy/util-defaults-mode-node/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5843,12 +5839,12 @@ } }, "node_modules/@smithy/util-defaults-mode-node/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5856,12 +5852,12 @@ } }, "node_modules/@smithy/util-defaults-mode-node/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5869,9 +5865,9 @@ } }, "node_modules/@smithy/util-defaults-mode-node/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5881,13 +5877,13 @@ } }, "node_modules/@smithy/util-endpoints": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.1.2.tgz", - "integrity": "sha512-+AJsaaEGb5ySvf1SKMRrPZdYHRYSzMkCoK16jWnIMpREAnflVspMIDeCVSZJuj+5muZfgGpNpijE3mUNtjv01Q==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.2.1.tgz", + "integrity": "sha512-lJudabG/ll+BD22i8IgxZgxS+1hEdUfFqtC1tNubC9vlGwInUktcXodTe5CvM+xDiqGZfqYLY7mKFdabCIrkYw==", "license": "Apache-2.0", "dependencies": { - "@smithy/node-config-provider": "^4.2.2", - "@smithy/types": "^4.5.0", + "@smithy/node-config-provider": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5895,14 +5891,14 @@ } }, "node_modules/@smithy/util-endpoints/node_modules/@smithy/node-config-provider": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.2.2.tgz", - "integrity": "sha512-SYGTKyPvyCfEzIN5rD8q/bYaOPZprYUPD2f5g9M7OjaYupWOoQFYJ5ho+0wvxIRf471i2SR4GoiZ2r94Jq9h6A==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.1.tgz", + "integrity": "sha512-Ap8Wd95HCrWRktMAZNc0AVzdPdUSPHsG59+DMe+4aH74FLDnVTo/7XDcRhSkSZCHeDjaDtzAh5OvnHOE0VHwUg==", "license": "Apache-2.0", "dependencies": { - "@smithy/property-provider": "^4.1.1", - "@smithy/shared-ini-file-loader": "^4.2.0", - "@smithy/types": "^4.5.0", + "@smithy/property-provider": "^4.2.1", + "@smithy/shared-ini-file-loader": "^4.3.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5910,12 +5906,12 @@ } }, "node_modules/@smithy/util-endpoints/node_modules/@smithy/property-provider": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.1.1.tgz", - "integrity": "sha512-gm3ZS7DHxUbzC2wr8MUCsAabyiXY0gaj3ROWnhSx/9sPMc6eYLMM4rX81w1zsMaObj2Lq3PZtNCC1J6lpEY7zg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.1.tgz", + "integrity": "sha512-2zthf6j/u4XV3nRvulJgQsZdAs9xNf7dJPE5+Wvrx4yAsNrmtchadydASqRLXEw67ovl8c+HFa58QEXD/jUMSg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5923,12 +5919,12 @@ } }, "node_modules/@smithy/util-endpoints/node_modules/@smithy/shared-ini-file-loader": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.2.0.tgz", - "integrity": "sha512-OQTfmIEp2LLuWdxa8nEEPhZmiOREO6bcB6pjs0AySf4yiZhl6kMOfqmcwcY8BaBPX+0Tb+tG7/Ia/6mwpoZ7Pw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.1.tgz", + "integrity": "sha512-V4XVUUCsuVeSNkjeXLR4Y5doyNkTx29Cp8NfKoklgpSsWawyxmJbVvJ1kFHRulOmdBlLuHoqDrAirN8ZoduUCA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5936,9 +5932,9 @@ } }, "node_modules/@smithy/util-endpoints/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -5971,13 +5967,13 @@ } }, "node_modules/@smithy/util-retry": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.1.1.tgz", - "integrity": "sha512-jGeybqEZ/LIordPLMh5bnmnoIgsqnp4IEimmUp5c5voZ8yx+5kAlN5+juyr7p+f7AtZTgvhmInQk4Q0UVbrZ0Q==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.2.1.tgz", + "integrity": "sha512-0DQqQtZ9brT/QCMts9ssPnsU6CmQAgzkAvTIGcTHoMbntQa7v5VPxxpiyyiTK/BIl8y0vCZSXcOS+kOMXAYRpg==", "license": "Apache-2.0", "dependencies": { - "@smithy/service-error-classification": "^4.1.1", - "@smithy/types": "^4.5.0", + "@smithy/service-error-classification": "^4.2.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -5985,9 +5981,9 @@ } }, "node_modules/@smithy/util-retry/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -6038,13 +6034,13 @@ } }, "node_modules/@smithy/util-waiter": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.1.1.tgz", - "integrity": "sha512-PJBmyayrlfxM7nbqjomF4YcT1sApQwZio0NHSsT0EzhJqljRmvhzqZua43TyEs80nJk2Cn2FGPg/N8phH6KeCQ==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.2.1.tgz", + "integrity": "sha512-c/tJR24Zf7TZFiq/cmVY9WH9j6j3WBDVvhfgCE9mtSb1u93A1P+qf4c7r6g8hcJOKm25Jp12uqojnB0T1//OmA==", "license": "Apache-2.0", "dependencies": { - "@smithy/abort-controller": "^4.1.1", - "@smithy/types": "^4.5.0", + "@smithy/abort-controller": "^4.2.1", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -6052,12 +6048,12 @@ } }, "node_modules/@smithy/util-waiter/node_modules/@smithy/abort-controller": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.1.1.tgz", - "integrity": "sha512-vkzula+IwRvPR6oKQhMYioM3A/oX/lFCZiwuxkQbRhqJS2S4YRY2k7k/SyR2jMf3607HLtbEwlRxi0ndXHMjRg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.1.tgz", + "integrity": "sha512-OvVe992TXYHR7QpYebmtw+/MF5AP9vU0fjfyfW1VmNYeA/dfibLhN13xrzIj+EO0HYMPur5lUIB9hRZ7IhjLDQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.5.0", + "@smithy/types": "^4.7.0", "tslib": "^2.6.2" }, "engines": { @@ -6065,9 +6061,21 @@ } }, "node_modules/@smithy/util-waiter/node_modules/@smithy/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.5.0.tgz", - "integrity": "sha512-RkUpIOsVlAwUIZXO1dsz8Zm+N72LClFfsNqf173catVlvRZiwPy0x2u0JLEA4byreOPKDZPGjmPDylMoP8ZJRg==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.7.0.tgz", + "integrity": "sha512-KM8Or+jCDCrUI3wYYhj7ehrC7aATB1NdJ1aFEE/YLKNLVH257k9RNeOqKdg0JOxjyEpVD7KKsmmob9mRy1Ho2g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/uuid": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@smithy/uuid/-/uuid-1.1.0.tgz", + "integrity": "sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" diff --git a/package.json b/package.json index b74242b1..1d163f45 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "dependencies": { "@actions/core": "^1.10.1", "@aws-sdk/client-codedeploy": "^3.888.0", - "@aws-sdk/client-ecs": "^3.883.0", + "@aws-sdk/client-ecs": "^3.908.0", "yaml": "^2.8.1" }, "devDependencies": {