feat: Complete zCode CLI X with Telegram bot integration

- Add full Telegram bot functionality with Z.AI API integration
- Implement 4 tools: Bash, FileEdit, WebSearch, Git
- Add 3 agents: Code Reviewer, Architect, DevOps Engineer
- Add 6 skills for common coding tasks
- Add systemd service file for 24/7 operation
- Add nginx configuration for HTTPS webhook
- Add comprehensive documentation
- Implement WebSocket server for real-time updates
- Add logging system with Winston
- Add environment validation

🤖 zCode CLI X - Agentic coder with Z.AI + Telegram integration
This commit is contained in:
admin
2026-05-05 09:01:26 +00:00
Unverified
parent 4a7035dd92
commit 875c7f9b91
24688 changed files with 3224957 additions and 221 deletions

View File

@@ -0,0 +1 @@
/home/uroma2/zcode-cli-x/~/.npm-cache/@smithy/abort-controller@2.2.0@@@1

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,4 @@
# @smithy/abort-controller
[![NPM version](https://img.shields.io/npm/v/@smithy/abort-controller/latest.svg)](https://www.npmjs.com/package/@smithy/abort-controller)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/abort-controller.svg)](https://www.npmjs.com/package/@smithy/abort-controller)

View File

@@ -0,0 +1 @@
module.exports = require("./index.js");

View File

@@ -0,0 +1 @@
module.exports = require("./index.js");

View File

@@ -0,0 +1,82 @@
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, {
AbortController: () => AbortController,
AbortHandler: () => import_types.AbortHandler,
AbortSignal: () => AbortSignal,
IAbortController: () => import_types.AbortController,
IAbortSignal: () => import_types.AbortSignal
});
module.exports = __toCommonJS(src_exports);
// src/AbortController.ts
// src/AbortSignal.ts
var import_types = require("@smithy/types");
var _AbortSignal = class _AbortSignal {
constructor() {
this.onabort = null;
this._aborted = false;
Object.defineProperty(this, "_aborted", {
value: false,
writable: true
});
}
/**
* Whether the associated operation has already been cancelled.
*/
get aborted() {
return this._aborted;
}
/**
* @internal
*/
abort() {
this._aborted = true;
if (this.onabort) {
this.onabort(this);
this.onabort = null;
}
}
};
__name(_AbortSignal, "AbortSignal");
var AbortSignal = _AbortSignal;
// src/AbortController.ts
var _AbortController = class _AbortController {
constructor() {
this.signal = new AbortSignal();
}
abort() {
this.signal.abort();
}
};
__name(_AbortController, "AbortController");
var AbortController = _AbortController;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AbortController,
AbortSignal
});

View File

@@ -0,0 +1,9 @@
import { AbortSignal } from "./AbortSignal";
export class AbortController {
constructor() {
this.signal = new AbortSignal();
}
abort() {
this.signal.abort();
}
}

View File

@@ -0,0 +1,20 @@
export class AbortSignal {
constructor() {
this.onabort = null;
this._aborted = false;
Object.defineProperty(this, "_aborted", {
value: false,
writable: true,
});
}
get aborted() {
return this._aborted;
}
abort() {
this._aborted = true;
if (this.onabort) {
this.onabort(this);
this.onabort = null;
}
}
}

View File

@@ -0,0 +1,2 @@
export * from "./AbortController";
export * from "./AbortSignal";

View File

@@ -0,0 +1,13 @@
import { AbortController as IAbortController } from "@smithy/types";
import { AbortSignal } from "./AbortSignal";
export { IAbortController };
/**
* This implementation was added as Node.js didn't support AbortController prior to 15.x
* Use native implementation in browsers or Node.js \>=15.4.0.
*
* @public
*/
export declare class AbortController implements IAbortController {
readonly signal: AbortSignal;
abort(): void;
}

View File

@@ -0,0 +1,18 @@
import { AbortHandler, AbortSignal as IAbortSignal } from "@smithy/types";
export { AbortHandler, IAbortSignal };
/**
* @public
*/
export declare class AbortSignal implements IAbortSignal {
onabort: AbortHandler | null;
private _aborted;
constructor();
/**
* Whether the associated operation has already been cancelled.
*/
get aborted(): boolean;
/**
* @internal
*/
abort(): void;
}

View File

@@ -0,0 +1,9 @@
/**
* This implementation was added as Node.js didn't support AbortController prior to 15.x
* Use native implementation in browsers or Node.js \>=15.4.0.
*
* @deprecated Use standard implementations in [Browsers](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and [Node.js](https://nodejs.org/docs/latest/api/globals.html#class-abortcontroller)
* @packageDocumentation
*/
export * from "./AbortController";
export * from "./AbortSignal";

View File

@@ -0,0 +1,13 @@
import { AbortController as IAbortController } from "@smithy/types";
import { AbortSignal } from "./AbortSignal";
export { IAbortController };
/**
* This implementation was added as Node.js didn't support AbortController prior to 15.x
* Use native implementation in browsers or Node.js \>=15.4.0.
*
* @public
*/
export declare class AbortController implements IAbortController {
readonly signal: AbortSignal;
abort(): void;
}

View File

@@ -0,0 +1,18 @@
import { AbortHandler, AbortSignal as IAbortSignal } from "@smithy/types";
export { AbortHandler, IAbortSignal };
/**
* @public
*/
export declare class AbortSignal implements IAbortSignal {
onabort: AbortHandler | null;
private _aborted;
constructor();
/*
* Whether the associated operation has already been cancelled.
*/
readonly aborted: boolean;
/**
* @internal
*/
abort(): void;
}

View File

@@ -0,0 +1,9 @@
/**
* This implementation was added as Node.js didn't support AbortController prior to 15.x
* Use native implementation in browsers or Node.js \>=15.4.0.
*
* @deprecated Use standard implementations in [Browsers](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and [Node.js](https://nodejs.org/docs/latest/api/globals.html#class-abortcontroller)
* @packageDocumentation
*/
export * from "./AbortController";
export * from "./AbortSignal";

View File

@@ -0,0 +1,62 @@
{
"name": "@smithy/abort-controller",
"version": "2.2.0",
"description": "A simple abort controller library",
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"types": "./dist-types/index.d.ts",
"scripts": {
"build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types && yarn build:types:downlevel'",
"build:cjs": "node ../../scripts/inline abort-controller",
"build:es": "yarn g:tsc -p tsconfig.es.json",
"build:types": "yarn g:tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
"stage-release": "rimraf ./.release && yarn pack && mkdir ./.release && tar zxvf ./package.tgz --directory ./.release && rm ./package.tgz",
"clean": "rimraf ./dist-* && rimraf *.tsbuildinfo || exit 0",
"lint": "eslint -c ../../.eslintrc.js \"src/**/*.ts\"",
"format": "prettier --config ../../prettier.config.js --ignore-path ../.prettierignore --write \"**/*.{ts,md,json}\"",
"extract:docs": "api-extractor run --local",
"test": "yarn g:jest"
},
"author": {
"name": "AWS SDK for JavaScript Team",
"url": "https://aws.amazon.com/javascript/"
},
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^2.12.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=14.0.0"
},
"typesVersions": {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
"files": [
"dist-*/**"
],
"homepage": "https://github.com/awslabs/smithy-typescript/tree/main/packages/abort-controller",
"repository": {
"type": "git",
"url": "https://github.com/awslabs/smithy-typescript.git",
"directory": "packages/abort-controller"
},
"devDependencies": {
"@tsconfig/recommended": "1.0.1",
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"rimraf": "3.0.2",
"typedoc": "0.23.23"
},
"typedoc": {
"entryPoint": "src/index.ts"
},
"publishConfig": {
"directory": ".release/package"
}
}

View File

@@ -0,0 +1 @@
/home/uroma2/zcode-cli-x/~/.npm-cache/@smithy/config-resolver@4.4.13@@@1

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,10 @@
# @smithy/config-resolver
[![NPM version](https://img.shields.io/npm/v/@smithy/config-resolver/latest.svg)](https://www.npmjs.com/package/@smithy/config-resolver)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/config-resolver.svg)](https://www.npmjs.com/package/@smithy/config-resolver)
> An internal package
## Usage
You probably shouldn't, at least directly.

View File

@@ -0,0 +1,198 @@
'use strict';
var utilConfigProvider = require('@smithy/util-config-provider');
var utilMiddleware = require('@smithy/util-middleware');
var utilEndpoints = require('@smithy/util-endpoints');
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 nodeDualstackConfigSelectors = {
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: undefined,
};
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 nodeFipsConfigSelectors = {
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: undefined,
};
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),
});
};
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,
});
};
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");
},
};
const NODE_REGION_CONFIG_FILE_OPTIONS = {
preferredFile: "credentials",
};
const validRegions = new Set();
const checkRegion = (region, check = utilEndpoints.isValidHostLabel) => {
if (!validRegions.has(region) && !check(region)) {
if (region === "*") {
console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`);
}
else {
throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);
}
}
else {
validRegions.add(region);
}
};
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");
}
return Object.assign(input, {
region: async () => {
const providedRegion = typeof region === "function" ? await region() : region;
const realRegion = getRealRegion(providedRegion);
checkRegion(realRegion);
return realRegion;
},
useFipsEndpoint: async () => {
const providedRegion = typeof region === "string" ? region : await region();
if (isFipsRegion(providedRegion)) {
return true;
}
return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
},
});
};
const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname;
const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname
? regionHostname
: partitionHostname
? partitionHostname.replace("{region}", resolvedRegion)
: undefined;
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,
}),
};
};
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.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors;
exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors;
exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig;
exports.resolveEndpointsConfig = resolveEndpointsConfig;
exports.resolveRegionConfig = resolveRegionConfig;

View File

@@ -0,0 +1,14 @@
import { booleanSelector, SelectorType } from "@smithy/util-config-provider";
export const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
export const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
export const DEFAULT_USE_DUALSTACK_ENDPOINT = false;
export const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV),
configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG),
default: false,
};
export const nodeDualstackConfigSelectors = {
environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV),
configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG),
default: undefined,
};

View File

@@ -0,0 +1,14 @@
import { booleanSelector, SelectorType } from "@smithy/util-config-provider";
export const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
export const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
export const DEFAULT_USE_FIPS_ENDPOINT = false;
export const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV),
configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG),
default: false,
};
export const nodeFipsConfigSelectors = {
environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV),
configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG),
default: undefined,
};

View File

@@ -0,0 +1,4 @@
export * from "./NodeUseDualstackEndpointConfigOptions";
export * from "./NodeUseFipsEndpointConfigOptions";
export * from "./resolveCustomEndpointsConfig";
export * from "./resolveEndpointsConfig";

View File

@@ -0,0 +1,10 @@
import { normalizeProvider } from "@smithy/util-middleware";
export const resolveCustomEndpointsConfig = (input) => {
const { tls, endpoint, urlParser, useDualstackEndpoint } = input;
return Object.assign(input, {
tls: tls ?? true,
endpoint: normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint),
isCustomEndpoint: true,
useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),
});
};

View File

@@ -0,0 +1,14 @@
import { normalizeProvider } from "@smithy/util-middleware";
import { getEndpointFromRegion } from "./utils/getEndpointFromRegion";
export const resolveEndpointsConfig = (input) => {
const useDualstackEndpoint = normalizeProvider(input.useDualstackEndpoint ?? false);
const { endpoint, useFipsEndpoint, urlParser, tls } = input;
return Object.assign(input, {
tls: tls ?? true,
endpoint: endpoint
? normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint)
: () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),
isCustomEndpoint: !!endpoint,
useDualstackEndpoint,
});
};

View File

@@ -0,0 +1,15 @@
export 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}`);
};

View File

@@ -0,0 +1,3 @@
export * from "./endpointsConfig";
export * from "./regionConfig";
export * from "./regionInfo";

View File

@@ -0,0 +1,15 @@
import { isValidHostLabel } from "@smithy/util-endpoints";
const validRegions = new Set();
export const checkRegion = (region, check = isValidHostLabel) => {
if (!validRegions.has(region) && !check(region)) {
if (region === "*") {
console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`);
}
else {
throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);
}
}
else {
validRegions.add(region);
}
};

View File

@@ -0,0 +1,12 @@
export const REGION_ENV_NAME = "AWS_REGION";
export const REGION_INI_NAME = "region";
export const NODE_REGION_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => env[REGION_ENV_NAME],
configFileSelector: (profile) => profile[REGION_INI_NAME],
default: () => {
throw new Error("Region is missing");
},
};
export const NODE_REGION_CONFIG_FILE_OPTIONS = {
preferredFile: "credentials",
};

View File

@@ -0,0 +1,6 @@
import { isFipsRegion } from "./isFipsRegion";
export const getRealRegion = (region) => isFipsRegion(region)
? ["fips-aws-global", "aws-fips"].includes(region)
? "us-east-1"
: region.replace(/fips-(dkr-|prod-)?|-fips/, "")
: region;

View File

@@ -0,0 +1,2 @@
export * from "./config";
export * from "./resolveRegionConfig";

View File

@@ -0,0 +1 @@
export const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));

View File

@@ -0,0 +1,24 @@
import { checkRegion } from "./checkRegion";
import { getRealRegion } from "./getRealRegion";
import { isFipsRegion } from "./isFipsRegion";
export const resolveRegionConfig = (input) => {
const { region, useFipsEndpoint } = input;
if (!region) {
throw new Error("Region is missing");
}
return Object.assign(input, {
region: async () => {
const providedRegion = typeof region === "function" ? await region() : region;
const realRegion = getRealRegion(providedRegion);
checkRegion(realRegion);
return realRegion;
},
useFipsEndpoint: async () => {
const providedRegion = typeof region === "string" ? region : await region();
if (isFipsRegion(providedRegion)) {
return true;
}
return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
},
});
};

View File

@@ -0,0 +1 @@
export const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname;

View File

@@ -0,0 +1,29 @@
import { getHostnameFromVariants } from "./getHostnameFromVariants";
import { getResolvedHostname } from "./getResolvedHostname";
import { getResolvedPartition } from "./getResolvedPartition";
import { getResolvedSigningRegion } from "./getResolvedSigningRegion";
export 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,
}),
};
};

View File

@@ -0,0 +1,5 @@
export const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname
? regionHostname
: partitionHostname
? partitionHostname.replace("{region}", resolvedRegion)
: undefined;

View File

@@ -0,0 +1 @@
export const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws";

View File

@@ -0,0 +1,12 @@
export 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);
}
}
};

View File

@@ -0,0 +1,3 @@
export * from "./PartitionHash";
export * from "./RegionHash";
export * from "./getRegionInfo";

View File

@@ -0,0 +1,23 @@
import type { LoadedConfigSelectors } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
/**
* @internal
*/
export declare const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
/**
* @internal
*/
export declare const DEFAULT_USE_DUALSTACK_ENDPOINT = false;
/**
* Don't delete this, used by older clients.
* @deprecated replaced by nodeDualstackConfigSelectors in newer clients.
* @internal
*/
export declare const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: LoadedConfigSelectors<boolean>;
/**
* @internal
*/
export declare const nodeDualstackConfigSelectors: LoadedConfigSelectors<boolean | undefined>;

View File

@@ -0,0 +1,23 @@
import type { LoadedConfigSelectors } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
/**
* @internal
*/
export declare const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
/**
* @internal
*/
export declare const DEFAULT_USE_FIPS_ENDPOINT = false;
/**
* Don't delete this, used by older clients.
* @deprecated replaced by nodeFipsConfigSelectors in newer clients.
* @internal
*/
export declare const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: LoadedConfigSelectors<boolean>;
/**
* @internal
*/
export declare const nodeFipsConfigSelectors: LoadedConfigSelectors<boolean | undefined>;

View File

@@ -0,0 +1,16 @@
/**
* @internal
*/
export * from "./NodeUseDualstackEndpointConfigOptions";
/**
* @internal
*/
export * from "./NodeUseFipsEndpointConfigOptions";
/**
* @internal
*/
export * from "./resolveCustomEndpointsConfig";
/**
* @internal
*/
export * from "./resolveEndpointsConfig";

View File

@@ -0,0 +1,37 @@
import type { Endpoint, Provider, UrlParser } from "@smithy/types";
import type { EndpointsInputConfig, EndpointsResolvedConfig } from "./resolveEndpointsConfig";
/**
* @public
* @deprecated superseded by default endpointRuleSet generation.
*/
export interface CustomEndpointsInputConfig extends EndpointsInputConfig {
/**
* The fully qualified endpoint of the webservice.
*/
endpoint: string | Endpoint | Provider<Endpoint>;
}
/**
* @internal
* @deprecated superseded by default endpointRuleSet generation.
*/
interface PreviouslyResolved {
urlParser: UrlParser;
}
/**
* @internal
* @deprecated superseded by default endpointRuleSet generation.
*/
export interface CustomEndpointsResolvedConfig extends EndpointsResolvedConfig {
/**
* Whether the endpoint is specified by caller.
* @internal
*/
isCustomEndpoint: true;
}
/**
* @internal
*
* @deprecated superseded by default endpointRuleSet generation.
*/
export declare const resolveCustomEndpointsConfig: <T>(input: T & CustomEndpointsInputConfig & PreviouslyResolved) => T & CustomEndpointsResolvedConfig;
export {};

View File

@@ -0,0 +1,57 @@
import type { Endpoint, Provider, RegionInfoProvider, UrlParser } from "@smithy/types";
/**
* @public
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
export interface EndpointsInputConfig {
/**
* The fully qualified endpoint of the webservice. This is only required when using
* a custom endpoint (for example, when using a local version of S3).
*/
endpoint?: string | Endpoint | Provider<Endpoint>;
/**
* Whether TLS is enabled for requests.
*/
tls?: boolean;
/**
* Enables IPv6/IPv4 dualstack endpoint.
*/
useDualstackEndpoint?: boolean | Provider<boolean>;
}
/**
* @internal
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
interface PreviouslyResolved {
regionInfoProvider: RegionInfoProvider;
urlParser: UrlParser;
region: Provider<string>;
useFipsEndpoint: Provider<boolean>;
}
/**
* @internal
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
export interface EndpointsResolvedConfig extends Required<EndpointsInputConfig> {
/**
* Resolved value for input {@link EndpointsInputConfig.endpoint}
*/
endpoint: Provider<Endpoint>;
/**
* Whether the endpoint is specified by caller.
* @internal
*/
isCustomEndpoint?: boolean;
/**
* Resolved value for input {@link EndpointsInputConfig.useDualstackEndpoint}
*/
useDualstackEndpoint: Provider<boolean>;
}
/**
* @internal
*
* @deprecated endpoints rulesets use \@smithy/middleware-endpoint resolveEndpointConfig.
* All generated clients should migrate to Endpoints 2.0 endpointRuleSet traits.
*/
export declare const resolveEndpointsConfig: <T>(input: T & EndpointsInputConfig & PreviouslyResolved) => T & EndpointsResolvedConfig;
export {};

View File

@@ -0,0 +1,11 @@
import type { Provider, RegionInfoProvider, UrlParser } from "@smithy/types";
interface GetEndpointFromRegionOptions {
region: Provider<string>;
tls?: boolean;
regionInfoProvider: RegionInfoProvider;
urlParser: UrlParser;
useDualstackEndpoint: Provider<boolean>;
useFipsEndpoint: Provider<boolean>;
}
export declare const getEndpointFromRegion: (input: GetEndpointFromRegionOptions) => Promise<import("@smithy/types").Endpoint>;
export {};

View File

@@ -0,0 +1,12 @@
/**
* @internal
*/
export * from "./endpointsConfig";
/**
* @internal
*/
export * from "./regionConfig";
/**
* @internal
*/
export * from "./regionInfo";

View File

@@ -0,0 +1,9 @@
/**
* Checks whether region can be a host component.
*
* @param region - to check.
* @param check - checking function.
*
* @internal
*/
export declare const checkRegion: (region: string, check?: (value: string, allowSubDomains?: boolean) => boolean) => void;

View File

@@ -0,0 +1,17 @@
import type { LoadedConfigSelectors, LocalConfigOptions } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const REGION_ENV_NAME = "AWS_REGION";
/**
* @internal
*/
export declare const REGION_INI_NAME = "region";
/**
* @internal
*/
export declare const NODE_REGION_CONFIG_OPTIONS: LoadedConfigSelectors<string>;
/**
* @internal
*/
export declare const NODE_REGION_CONFIG_FILE_OPTIONS: LocalConfigOptions;

View File

@@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const getRealRegion: (region: string) => string;

View File

@@ -0,0 +1,8 @@
/**
* @internal
*/
export * from "./config";
/**
* @internal
*/
export * from "./resolveRegionConfig";

View File

@@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const isFipsRegion: (region: string) => boolean;

View File

@@ -0,0 +1,34 @@
import type { Provider } from "@smithy/types";
/**
* @public
*/
export interface RegionInputConfig {
/**
* The AWS region to which this client will send requests
*/
region?: string | Provider<string>;
/**
* Enables FIPS compatible endpoints.
*/
useFipsEndpoint?: boolean | Provider<boolean>;
}
interface PreviouslyResolved {
}
/**
* @internal
*/
export interface RegionResolvedConfig {
/**
* Resolved value for input config {@link RegionInputConfig.region}
*/
region: Provider<string>;
/**
* Resolved value for input {@link RegionInputConfig.useFipsEndpoint}
*/
useFipsEndpoint: Provider<boolean>;
}
/**
* @internal
*/
export declare const resolveRegionConfig: <T>(input: T & RegionInputConfig & PreviouslyResolved) => T & RegionResolvedConfig;
export {};

View File

@@ -0,0 +1,11 @@
import type { EndpointVariantTag } from "./EndpointVariantTag";
/**
* Provides hostname information for specific host label.
*
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export type EndpointVariant = {
hostname: string;
tags: EndpointVariantTag[];
};

View File

@@ -0,0 +1,10 @@
/**
*
*
* The tag which mentions which area variant is providing information for.
* Can be either "fips" or "dualstack".
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type EndpointVariantTag = "fips" | "dualstack";

View File

@@ -0,0 +1,15 @@
import type { EndpointVariant } from "./EndpointVariant";
/**
* The hash of partition with the information specific to that partition.
* The information includes the list of regions belonging to that partition,
* and the hostname to be used for the partition.
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type PartitionHash = Record<string, {
regions: string[];
regionRegex: string;
variants: EndpointVariant[];
endpoint?: string;
}>;

View File

@@ -0,0 +1,13 @@
import type { EndpointVariant } from "./EndpointVariant";
/**
* The hash of region with the information specific to that region.
* The information can include hostname, signingService and signingRegion.
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type RegionHash = Record<string, {
variants: EndpointVariant[];
signingService?: string;
signingRegion?: string;
}>;

View File

@@ -0,0 +1,14 @@
import type { EndpointVariant } from "./EndpointVariant";
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export interface GetHostnameFromVariantsOptions {
useFipsEndpoint: boolean;
useDualstackEndpoint: boolean;
}
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export declare const getHostnameFromVariants: (variants: EndpointVariant[] | undefined, { useFipsEndpoint, useDualstackEndpoint }: GetHostnameFromVariantsOptions) => string | undefined;

View File

@@ -0,0 +1,19 @@
import type { RegionInfo } from "@smithy/types";
import type { PartitionHash } from "./PartitionHash";
import type { RegionHash } from "./RegionHash";
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export interface GetRegionInfoOptions {
useFipsEndpoint?: boolean;
useDualstackEndpoint?: boolean;
signingService: string;
regionHash: RegionHash;
partitionHash: PartitionHash;
}
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export declare const getRegionInfo: (region: string, { useFipsEndpoint, useDualstackEndpoint, signingService, regionHash, partitionHash, }: GetRegionInfoOptions) => RegionInfo;

View File

@@ -0,0 +1,13 @@
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedHostnameOptions {
regionHostname?: string;
partitionHostname?: string;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedHostname: (resolvedRegion: string, { regionHostname, partitionHostname }: GetResolvedHostnameOptions) => string | undefined;

View File

@@ -0,0 +1,13 @@
import type { PartitionHash } from "./PartitionHash";
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedPartitionOptions {
partitionHash: PartitionHash;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedPartition: (region: string, { partitionHash }: GetResolvedPartitionOptions) => string;

View File

@@ -0,0 +1,14 @@
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedSigningRegionOptions {
regionRegex: string;
signingRegion?: string;
useFipsEndpoint: boolean;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedSigningRegion: (hostname: string, { signingRegion, regionRegex, useFipsEndpoint }: GetResolvedSigningRegionOptions) => string | undefined;

View File

@@ -0,0 +1,12 @@
/**
* @internal
*/
export * from "./PartitionHash";
/**
* @internal
*/
export * from "./RegionHash";
/**
* @internal
*/
export * from "./getRegionInfo";

View File

@@ -0,0 +1,23 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
/**
* @internal
*/
export declare const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
/**
* @internal
*/
export declare const DEFAULT_USE_DUALSTACK_ENDPOINT = false;
/**
* Don't delete this, used by older clients.
* @deprecated replaced by nodeDualstackConfigSelectors in newer clients.
* @internal
*/
export declare const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: LoadedConfigSelectors<boolean>;
/**
* @internal
*/
export declare const nodeDualstackConfigSelectors: LoadedConfigSelectors<boolean | undefined>;

View File

@@ -0,0 +1,23 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
/**
* @internal
*/
export declare const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
/**
* @internal
*/
export declare const DEFAULT_USE_FIPS_ENDPOINT = false;
/**
* Don't delete this, used by older clients.
* @deprecated replaced by nodeFipsConfigSelectors in newer clients.
* @internal
*/
export declare const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: LoadedConfigSelectors<boolean>;
/**
* @internal
*/
export declare const nodeFipsConfigSelectors: LoadedConfigSelectors<boolean | undefined>;

View File

@@ -0,0 +1,16 @@
/**
* @internal
*/
export * from "./NodeUseDualstackEndpointConfigOptions";
/**
* @internal
*/
export * from "./NodeUseFipsEndpointConfigOptions";
/**
* @internal
*/
export * from "./resolveCustomEndpointsConfig";
/**
* @internal
*/
export * from "./resolveEndpointsConfig";

View File

@@ -0,0 +1,37 @@
import { Endpoint, Provider, UrlParser } from "@smithy/types";
import { EndpointsInputConfig, EndpointsResolvedConfig } from "./resolveEndpointsConfig";
/**
* @public
* @deprecated superseded by default endpointRuleSet generation.
*/
export interface CustomEndpointsInputConfig extends EndpointsInputConfig {
/**
* The fully qualified endpoint of the webservice.
*/
endpoint: string | Endpoint | Provider<Endpoint>;
}
/**
* @internal
* @deprecated superseded by default endpointRuleSet generation.
*/
interface PreviouslyResolved {
urlParser: UrlParser;
}
/**
* @internal
* @deprecated superseded by default endpointRuleSet generation.
*/
export interface CustomEndpointsResolvedConfig extends EndpointsResolvedConfig {
/**
* Whether the endpoint is specified by caller.
* @internal
*/
isCustomEndpoint: true;
}
/**
* @internal
*
* @deprecated superseded by default endpointRuleSet generation.
*/
export declare const resolveCustomEndpointsConfig: <T>(input: T & CustomEndpointsInputConfig & PreviouslyResolved) => T & CustomEndpointsResolvedConfig;
export {};

View File

@@ -0,0 +1,57 @@
import { Endpoint, Provider, RegionInfoProvider, UrlParser } from "@smithy/types";
/**
* @public
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
export interface EndpointsInputConfig {
/**
* The fully qualified endpoint of the webservice. This is only required when using
* a custom endpoint (for example, when using a local version of S3).
*/
endpoint?: string | Endpoint | Provider<Endpoint>;
/**
* Whether TLS is enabled for requests.
*/
tls?: boolean;
/**
* Enables IPv6/IPv4 dualstack endpoint.
*/
useDualstackEndpoint?: boolean | Provider<boolean>;
}
/**
* @internal
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
interface PreviouslyResolved {
regionInfoProvider: RegionInfoProvider;
urlParser: UrlParser;
region: Provider<string>;
useFipsEndpoint: Provider<boolean>;
}
/**
* @internal
* @deprecated see \@smithy/middleware-endpoint resolveEndpointConfig.
*/
export interface EndpointsResolvedConfig extends Required<EndpointsInputConfig> {
/**
* Resolved value for input {@link EndpointsInputConfig.endpoint}
*/
endpoint: Provider<Endpoint>;
/**
* Whether the endpoint is specified by caller.
* @internal
*/
isCustomEndpoint?: boolean;
/**
* Resolved value for input {@link EndpointsInputConfig.useDualstackEndpoint}
*/
useDualstackEndpoint: Provider<boolean>;
}
/**
* @internal
*
* @deprecated endpoints rulesets use \@smithy/middleware-endpoint resolveEndpointConfig.
* All generated clients should migrate to Endpoints 2.0 endpointRuleSet traits.
*/
export declare const resolveEndpointsConfig: <T>(input: T & EndpointsInputConfig & PreviouslyResolved) => T & EndpointsResolvedConfig;
export {};

View File

@@ -0,0 +1,11 @@
import { Provider, RegionInfoProvider, UrlParser } from "@smithy/types";
interface GetEndpointFromRegionOptions {
region: Provider<string>;
tls?: boolean;
regionInfoProvider: RegionInfoProvider;
urlParser: UrlParser;
useDualstackEndpoint: Provider<boolean>;
useFipsEndpoint: Provider<boolean>;
}
export declare const getEndpointFromRegion: (input: GetEndpointFromRegionOptions) => Promise<import("@smithy/types").Endpoint>;
export {};

View File

@@ -0,0 +1,12 @@
/**
* @internal
*/
export * from "./endpointsConfig";
/**
* @internal
*/
export * from "./regionConfig";
/**
* @internal
*/
export * from "./regionInfo";

View File

@@ -0,0 +1,9 @@
/**
* Checks whether region can be a host component.
*
* @param region - to check.
* @param check - checking function.
*
* @internal
*/
export declare const checkRegion: (region: string, check?: (value: string, allowSubDomains?: boolean) => boolean) => void;

View File

@@ -0,0 +1,17 @@
import { LoadedConfigSelectors, LocalConfigOptions } from "@smithy/node-config-provider";
/**
* @internal
*/
export declare const REGION_ENV_NAME = "AWS_REGION";
/**
* @internal
*/
export declare const REGION_INI_NAME = "region";
/**
* @internal
*/
export declare const NODE_REGION_CONFIG_OPTIONS: LoadedConfigSelectors<string>;
/**
* @internal
*/
export declare const NODE_REGION_CONFIG_FILE_OPTIONS: LocalConfigOptions;

View File

@@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const getRealRegion: (region: string) => string;

View File

@@ -0,0 +1,8 @@
/**
* @internal
*/
export * from "./config";
/**
* @internal
*/
export * from "./resolveRegionConfig";

View File

@@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const isFipsRegion: (region: string) => boolean;

View File

@@ -0,0 +1,34 @@
import { Provider } from "@smithy/types";
/**
* @public
*/
export interface RegionInputConfig {
/**
* The AWS region to which this client will send requests
*/
region?: string | Provider<string>;
/**
* Enables FIPS compatible endpoints.
*/
useFipsEndpoint?: boolean | Provider<boolean>;
}
interface PreviouslyResolved {
}
/**
* @internal
*/
export interface RegionResolvedConfig {
/**
* Resolved value for input config {@link RegionInputConfig.region}
*/
region: Provider<string>;
/**
* Resolved value for input {@link RegionInputConfig.useFipsEndpoint}
*/
useFipsEndpoint: Provider<boolean>;
}
/**
* @internal
*/
export declare const resolveRegionConfig: <T>(input: T & RegionInputConfig & PreviouslyResolved) => T & RegionResolvedConfig;
export {};

View File

@@ -0,0 +1,11 @@
import { EndpointVariantTag } from "./EndpointVariantTag";
/**
* Provides hostname information for specific host label.
*
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export type EndpointVariant = {
hostname: string;
tags: EndpointVariantTag[];
};

View File

@@ -0,0 +1,10 @@
/**
*
*
* The tag which mentions which area variant is providing information for.
* Can be either "fips" or "dualstack".
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type EndpointVariantTag = "fips" | "dualstack";

View File

@@ -0,0 +1,15 @@
import { EndpointVariant } from "./EndpointVariant";
/**
* The hash of partition with the information specific to that partition.
* The information includes the list of regions belonging to that partition,
* and the hostname to be used for the partition.
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type PartitionHash = Record<string, {
regions: string[];
regionRegex: string;
variants: EndpointVariant[];
endpoint?: string;
}>;

View File

@@ -0,0 +1,13 @@
import { EndpointVariant } from "./EndpointVariant";
/**
* The hash of region with the information specific to that region.
* The information can include hostname, signingService and signingRegion.
*
* @internal
* @deprecated unused for endpointRuleSets.
*/
export type RegionHash = Record<string, {
variants: EndpointVariant[];
signingService?: string;
signingRegion?: string;
}>;

View File

@@ -0,0 +1,14 @@
import { EndpointVariant } from "./EndpointVariant";
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export interface GetHostnameFromVariantsOptions {
useFipsEndpoint: boolean;
useDualstackEndpoint: boolean;
}
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export declare const getHostnameFromVariants: (variants: EndpointVariant[] | undefined, { useFipsEndpoint, useDualstackEndpoint }: GetHostnameFromVariantsOptions) => string | undefined;

View File

@@ -0,0 +1,19 @@
import { RegionInfo } from "@smithy/types";
import { PartitionHash } from "./PartitionHash";
import { RegionHash } from "./RegionHash";
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export interface GetRegionInfoOptions {
useFipsEndpoint?: boolean;
useDualstackEndpoint?: boolean;
signingService: string;
regionHash: RegionHash;
partitionHash: PartitionHash;
}
/**
* @internal
* @deprecated unused as of endpointsRuleSets.
*/
export declare const getRegionInfo: (region: string, { useFipsEndpoint, useDualstackEndpoint, signingService, regionHash, partitionHash, }: GetRegionInfoOptions) => RegionInfo;

View File

@@ -0,0 +1,13 @@
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedHostnameOptions {
regionHostname?: string;
partitionHostname?: string;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedHostname: (resolvedRegion: string, { regionHostname, partitionHostname }: GetResolvedHostnameOptions) => string | undefined;

View File

@@ -0,0 +1,13 @@
import { PartitionHash } from "./PartitionHash";
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedPartitionOptions {
partitionHash: PartitionHash;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedPartition: (region: string, { partitionHash }: GetResolvedPartitionOptions) => string;

View File

@@ -0,0 +1,14 @@
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export interface GetResolvedSigningRegionOptions {
regionRegex: string;
signingRegion?: string;
useFipsEndpoint: boolean;
}
/**
* @internal
* @deprecated unused for endpointRuleSets.
*/
export declare const getResolvedSigningRegion: (hostname: string, { signingRegion, regionRegex, useFipsEndpoint }: GetResolvedSigningRegionOptions) => string | undefined;

View File

@@ -0,0 +1,12 @@
/**
* @internal
*/
export * from "./PartitionHash";
/**
* @internal
*/
export * from "./RegionHash";
/**
* @internal
*/
export * from "./getRegionInfo";

View File

@@ -0,0 +1,66 @@
{
"name": "@smithy/config-resolver",
"version": "4.4.13",
"scripts": {
"build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types && yarn build:types:downlevel'",
"build:cjs": "node ../../scripts/inline config-resolver",
"build:es": "yarn g:tsc -p tsconfig.es.json",
"build:types": "yarn g:tsc -p tsconfig.types.json",
"build:types:downlevel": "premove dist-types/ts3.4 && downlevel-dts dist-types dist-types/ts3.4",
"stage-release": "premove .release && yarn pack && mkdir ./.release && tar zxvf ./package.tgz --directory ./.release && rm ./package.tgz",
"clean": "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
"lint": "eslint -c ../../.eslintrc.js \"src/**/*.ts\"",
"format": "prettier --config ../../prettier.config.js --ignore-path ../../.prettierignore --write \"**/*.{ts,md,json}\"",
"test": "yarn g:vitest run",
"extract:docs": "api-extractor run --local",
"test:watch": "yarn g:vitest watch"
},
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"types": "./dist-types/index.d.ts",
"author": {
"name": "AWS SDK for JavaScript Team",
"url": "https://aws.amazon.com/javascript/"
},
"license": "Apache-2.0",
"sideEffects": false,
"dependencies": {
"@smithy/node-config-provider": "^4.3.12",
"@smithy/types": "^4.13.1",
"@smithy/util-config-provider": "^4.2.2",
"@smithy/util-endpoints": "^3.3.3",
"@smithy/util-middleware": "^4.2.12",
"tslib": "^2.6.2"
},
"devDependencies": {
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"premove": "4.0.0",
"typedoc": "0.23.23"
},
"engines": {
"node": ">=18.0.0"
},
"typesVersions": {
"<4.5": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
"files": [
"dist-*/**"
],
"homepage": "https://github.com/smithy-lang/smithy-typescript/tree/main/packages/config-resolver",
"repository": {
"type": "git",
"url": "https://github.com/smithy-lang/smithy-typescript.git",
"directory": "packages/config-resolver"
},
"typedoc": {
"entryPoint": "src/index.ts"
},
"publishConfig": {
"directory": ".release/package"
}
}

View File

@@ -0,0 +1 @@
/home/uroma2/zcode-cli-x/~/.npm-cache/@smithy/core@3.23.13@@@1

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,56 @@
# @smithy/core
[![NPM version](https://img.shields.io/npm/v/@smithy/core/latest.svg)](https://www.npmjs.com/package/@smithy/core)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/core.svg)](https://www.npmjs.com/package/@smithy/core)
### :warning: Internal API :warning:
> This is an internal package.
> That means this is used as a dependency for other, public packages, but
> should not be taken directly as a dependency in your application's `package.json`.
> If you are updating the version of this package, for example to bring in a
> bug-fix, you should do so by updating your application lockfile with
> e.g. `npm up @scope/package` or equivalent command in another
> package manager, rather than taking a direct dependency.
---
This package provides common or core functionality for generic Smithy clients.
You do not need to explicitly install this package, since it will be installed during code generation if used.
## Development of `@smithy/core` submodules
Core submodules are organized for distribution via the `package.json` `exports` field.
`exports` is supported by default by the latest Node.js, webpack, and esbuild. For react-native, it can be
enabled via instructions found at [reactnative.dev/blog](https://reactnative.dev/blog/2023/06/21/package-exports-support), but we also provide a compatibility redirect.
Think of `@smithy/core` as a mono-package within the monorepo.
It preserves the benefits of modularization, for example to optimize Node.js initialization speed,
while making it easier to have a consistent version of core dependencies, reducing package sprawl when
installing a Smithy runtime client.
### Guide for submodules
- Each `index.ts` file corresponding to the pattern `./src/submodules/<MODULE_NAME>/index.ts` will be
published as a separate `dist-cjs` bundled submodule index using the `Inliner.js` build script.
- create a folder as `./src/submodules/<SUBMODULE>` including an `index.ts` file and a `README.md` file.
- The linter will throw an error on missing submodule metadata in `package.json` and the various `tsconfig.json` files, but it will automatically fix them if possible.
- a submodule is equivalent to a standalone `@smithy/<pkg>` package in that importing it in Node.js will resolve a separate bundle.
- submodules may not relatively import files from other submodules. Instead, directly use the `@scope/pkg/submodule` name as the import.
- The linter will check for this and throw an error.
- To the extent possible, correctly declaring submodule metadata is validated by the linter in `@smithy/core`.
The linter runs during `yarn build` and also as `yarn lint`.
### When should I create an `@smithy/core/submodule` vs. `@smithy/new-package`?
Keep in mind that the core package is installed by all downstream clients.
If the component functionality is upstream of multiple clients, it is
a good candidate for a core submodule. For example, if `middleware-retry` had been written
after the support for submodules was added, it would have been a submodule.
If the component's functionality is downstream of a client (rare), or only expected to be used by a very small
subset of clients, it could be written as a standalone package.

View File

@@ -0,0 +1,7 @@
/**
* Do not edit:
* This is a compatibility redirect for contexts that do not understand package.json exports field.
*/
declare module "@smithy/core/cbor" {
export * from "@smithy/core/dist-types/submodules/cbor/index.d";
}

View File

@@ -0,0 +1,6 @@
/**
* Do not edit:
* This is a compatibility redirect for contexts that do not understand package.json exports field.
*/
module.exports = require("./dist-cjs/submodules/cbor/index.js");

View File

@@ -0,0 +1,345 @@
'use strict';
var types = require('@smithy/types');
var utilMiddleware = require('@smithy/util-middleware');
var protocolHttp = require('@smithy/protocol-http');
var protocols = require('@smithy/core/protocols');
const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {});
const resolveAuthOptions = (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;
};
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);
};
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);
},
});
const httpAuthSchemeMiddlewareOptions = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "serializerMiddleware",
};
const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider,
}), httpAuthSchemeMiddlewareOptions);
},
});
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;
};
const httpSigningMiddlewareOptions = {
step: "finalizeRequest",
tags: ["HTTP_SIGNING"],
name: "httpSigningMiddleware",
aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
override: true,
relation: "after",
toMiddleware: "retryMiddleware",
};
const getHttpSigningPlugin = (config) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions);
},
});
const normalizeProvider = (input) => {
if (typeof input === "function")
return input;
const promisified = Promise.resolve(input);
return () => promisified;
};
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;
};
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;
};
};
exports.requestBuilder = 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;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,22 @@
'use strict';
var urlParser = require('@smithy/url-parser');
const toEndpointV1 = (endpoint) => {
if (typeof endpoint === "object") {
if ("url" in endpoint) {
const v1Endpoint = urlParser.parseUrl(endpoint.url);
if (endpoint.headers) {
v1Endpoint.headers = {};
for (const [name, values] of Object.entries(endpoint.headers)) {
v1Endpoint.headers[name.toLowerCase()] = values.join(", ");
}
}
return v1Endpoint;
}
return endpoint;
}
return urlParser.parseUrl(endpoint);
};
exports.toEndpointV1 = toEndpointV1;

View File

@@ -0,0 +1,259 @@
'use strict';
var utilUtf8 = require('@smithy/util-utf8');
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);
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";
}) ?? "";
const body = event[unionMember].body;
if (unionMember === "initial-response") {
const dataObject = await this.deserializer.read(responseSchema, body);
delete dataObject[eventStreamMember];
return {
[initialResponseMarker]: true,
...dataObject,
};
}
else if (unionMember in memberSchemas) {
const eventStreamSchema = memberSchemas[unionMember];
if (eventStreamSchema.isStructSchema()) {
const out = {};
let hasBindings = false;
for (const [name, member] of eventStreamSchema.structIterator()) {
const { eventHeader, eventPayload } = member.getMergedTraits();
hasBindings = hasBindings || Boolean(eventHeader || eventPayload);
if (eventPayload) {
if (member.isBlobSchema()) {
out[name] = body;
}
else if (member.isStringSchema()) {
out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body);
}
else if (member.isStructSchema()) {
out[name] = await this.deserializer.read(member, body);
}
}
else if (eventHeader) {
const value = event[unionMember].headers[name]?.value;
if (value != null) {
if (member.isNumericSchema()) {
if (value && typeof value === "object" && "bytes" in value) {
out[name] = BigInt(value.toString());
}
else {
out[name] = Number(value);
}
}
else {
out[name] = value;
}
}
}
}
if (hasBindings) {
return {
[unionMember]: out,
};
}
if (body.byteLength === 0) {
return {
[unionMember]: {},
};
}
}
return {
[unionMember]: await this.deserializer.read(eventStreamSchema, 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[4].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;
}
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 if (eventSchema.isUnitSchema()) {
serializer.write(eventSchema, {});
}
else {
throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.");
}
}
const messageSerialization = serializer.flush() ?? new Uint8Array();
const body = typeof messageSerialization === "string"
? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization)
: messageSerialization;
return {
body,
eventType,
explicitPayloadContentType,
additionalHeaders,
};
}
}
exports.EventStreamSerde = EventStreamSerde;

View File

@@ -0,0 +1,875 @@
'use strict';
var utilStream = require('@smithy/util-stream');
var schema = require('@smithy/core/schema');
var serde = require('@smithy/core/serde');
var protocolHttp = require('@smithy/protocol-http');
var utilBase64 = require('@smithy/util-base64');
var utilUtf8 = require('@smithy/util-utf8');
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);
};
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;
}
}
class HttpProtocol extends SerdeContext {
options;
compositeErrorRegistry;
constructor(options) {
super();
this.options = options;
this.compositeErrorRegistry = schema.TypeRegistry.for(options.defaultNamespace);
for (const etr of options.errorTypeRegistries ?? []) {
this.compositeErrorRegistry.copyFrom(etr);
}
}
getRequestType() {
return protocolHttp.HttpRequest;
}
getResponseType() {
return protocolHttp.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) : 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;
}
if (endpoint.headers) {
for (const [name, values] of Object.entries(endpoint.headers)) {
request.headers[name] = values.join(", ");
}
}
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,
};
if (endpoint.headers) {
for (const [name, value] of Object.entries(endpoint.headers)) {
request.headers[name] = value;
}
}
return request;
}
}
setHostPrefix(request, operationSchema, input) {
if (this.serdeContext?.disableHostPrefix) {
return;
}
const inputNs = schema.NormalizedSchema.of(operationSchema.input);
const opTraits = schema.translateTraits(operationSchema.traits ?? {});
if (opTraits.endpoint) {
let hostPrefix = opTraits.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"],
};
}
async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {
const eventStreamSerde = await this.loadEventStreamCapability();
return eventStreamSerde.serializeEventStream({
eventStream,
requestSchema,
initialRequest,
});
}
async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {
const eventStreamSerde = await this.loadEventStreamCapability();
return eventStreamSerde.deserializeEventStream({
response,
responseSchema,
initialResponseContainer,
});
}
async loadEventStreamCapability() {
const { EventStreamSerde } = await import('@smithy/core/event-streams');
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;
}
}
class HttpBindingProtocol extends HttpProtocol {
async serializeRequest(operationSchema, _input, context) {
const input = _input && typeof _input === "object" ? _input : {};
const serializer = this.serializer;
const query = {};
const headers = {};
const endpoint = await context.endpoint();
const ns = schema.NormalizedSchema.of(operationSchema?.input);
const payloadMemberNames = [];
const payloadMemberSchemas = [];
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 && !memberNs.isIdempotencyToken()) {
if (memberTraits.httpLabel) {
if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) {
throw new Error(`No value provided for input HTTP label: ${memberName}.`);
}
}
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();
}
}
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));
}
}
else if (memberTraits.httpHeader) {
serializer.write(memberNs, inputMemberValue);
headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush());
}
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();
}
}
else if (memberTraits.httpQuery || memberTraits.httpQueryParams) {
this.serializeQuery(memberNs, inputMemberValue, query);
}
else {
hasNonHttpBindingMember = true;
payloadMemberNames.push(memberName);
payloadMemberSchemas.push(memberNs);
}
}
if (hasNonHttpBindingMember && input) {
const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#");
const requiredMembers = ns.getSchema()[6];
const payloadSchema = [
3,
namespace,
name,
ns.getMergedTraits(),
payloadMemberNames,
payloadMemberSchemas,
undefined,
];
if (requiredMembers) {
payloadSchema[6] = requiredMembers;
}
else {
payloadSchema.pop();
}
serializer.write(payloadSchema, 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) {
if (dataFromBody[member] != null) {
dataObject[member] = dataFromBody[member];
}
}
}
}
else if (nonHttpBindingMembers.discardResponseBody) {
await collectBody(response.body, context);
}
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;
}
let discardResponseBody = true;
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) {
discardResponseBody = false;
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);
}
}
nonHttpBindingMembers.discardResponseBody = discardResponseBody;
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 input = _input && typeof _input === "object" ? _input : {};
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);
}
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 = Object.assign(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;
}
}
const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
if (input != null && input[memberName] !== undefined) {
const labelValue = labelValueProvider();
if (labelValue == null || 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));
}
else {
throw new Error("No value provided for input HTTP label: " + memberName + ".");
}
return resolvedPath;
};
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,
});
}
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;
}
}
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));
}
if (ns.isBlobSchema()) {
return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(data);
}
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;
}
base64ToUtf8(base64String) {
return (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)((this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(base64String));
}
}
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);
}
}
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:
if (ns.isIdempotencyToken()) {
this.stringBuffer = serde.generateIdempotencyToken();
}
else {
this.stringBuffer = String(value);
}
}
}
flush() {
const buffer = this.stringBuffer;
this.stringBuffer = "";
return buffer;
}
}
class HttpInterceptingShapeSerializer {
codecSerializer;
stringSerializer;
buffer;
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$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();
}
}
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;

Some files were not shown because too many files have changed in this diff Show More