UNPKG

recoder-code

Version:

🚀 AI-powered development platform - Chat with 32+ models, build projects, automate workflows. Free models included!

1,460 lines (1,433 loc) • 67.8 kB
"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 = require("@smithy/core/cbor"); var import_schema2 = require("@smithy/core/schema"); // src/submodules/protocols/ProtocolLib.ts var import_schema = require("@smithy/core/schema"); var import_util_body_length_browser = require("@smithy/util-body-length-browser"); 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 = require("@smithy/core/protocols"); var import_schema5 = require("@smithy/core/schema"); // 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 = require("@smithy/core/protocols"); var import_schema3 = require("@smithy/core/schema"); var import_serde2 = require("@smithy/core/serde"); var import_util_base64 = require("@smithy/util-base64"); // src/submodules/protocols/json/jsonReviver.ts var import_serde = require("@smithy/core/serde"); 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 = require("@smithy/smithy-client"); var import_util_utf8 = require("@smithy/util-utf8"); 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 = require("@smithy/core/protocols"); var import_schema4 = require("@smithy/core/schema"); var import_serde4 = require("@smithy/core/serde"); var import_util_base642 = require("@smithy/util-base64"); // src/submodules/protocols/json/jsonReplacer.ts var import_serde3 = require("@smithy/core/serde"); 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 = require("@smithy/core/protocols"); var import_schema6 = require("@smithy/core/schema"); 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 = require("@smithy/smithy-client"); 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 = require("@smithy/core/protocols"); var import_schema9 = require("@smithy/core/schema"); // src/submodules/protocols/xml/XmlShapeDeserializer.ts var import_protocols5 = require("@smithy/core/protocols"); var import_schema7 = require("@smithy/core/schema"); var import_smithy_client3 = require("@smithy/smithy-client"); var import_util_utf82 = require("@smithy/util-utf8"); var import_fast_xml_parser = require("fast-xml-parser"); 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 = require("@smithy/core/protocols"); var import_schema8 = require("@smithy/core/schema"); var import_serde5 = require("@smithy/core/serde"); var import_smithy_client4 = require("@smithy/smithy-client"); var import_util_base643 = require("@smithy/util-base64"); 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.