@naturalpay/sdk 0.1.4 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +119 -0
- package/LICENSE +7 -0
- package/README.md +340 -26
- package/api-promise.d.mts +2 -0
- package/api-promise.d.mts.map +1 -0
- package/api-promise.d.ts +2 -0
- package/api-promise.d.ts.map +1 -0
- package/api-promise.js +6 -0
- package/api-promise.js.map +1 -0
- package/api-promise.mjs +2 -0
- package/api-promise.mjs.map +1 -0
- package/client.d.mts +255 -0
- package/client.d.mts.map +1 -0
- package/client.d.ts +255 -0
- package/client.d.ts.map +1 -0
- package/client.js +548 -0
- package/client.js.map +1 -0
- package/client.mjs +544 -0
- package/client.mjs.map +1 -0
- package/core/api-promise.d.mts +46 -0
- package/core/api-promise.d.mts.map +1 -0
- package/core/api-promise.d.ts +46 -0
- package/core/api-promise.d.ts.map +1 -0
- package/core/api-promise.js +74 -0
- package/core/api-promise.js.map +1 -0
- package/core/api-promise.mjs +70 -0
- package/core/api-promise.mjs.map +1 -0
- package/core/error.d.mts +46 -0
- package/core/error.d.mts.map +1 -0
- package/core/error.d.ts +46 -0
- package/core/error.d.ts.map +1 -0
- package/core/error.js +113 -0
- package/core/error.js.map +1 -0
- package/core/error.mjs +97 -0
- package/core/error.mjs.map +1 -0
- package/core/resource.d.mts +6 -0
- package/core/resource.d.mts.map +1 -0
- package/core/resource.d.ts +6 -0
- package/core/resource.d.ts.map +1 -0
- package/core/resource.js +11 -0
- package/core/resource.js.map +1 -0
- package/core/resource.mjs +7 -0
- package/core/resource.mjs.map +1 -0
- package/core/uploads.d.mts +3 -0
- package/core/uploads.d.mts.map +1 -0
- package/core/uploads.d.ts +3 -0
- package/core/uploads.d.ts.map +1 -0
- package/core/uploads.js +6 -0
- package/core/uploads.js.map +1 -0
- package/core/uploads.mjs +2 -0
- package/core/uploads.mjs.map +1 -0
- package/error.d.mts +2 -0
- package/error.d.mts.map +1 -0
- package/error.d.ts +2 -0
- package/error.d.ts.map +1 -0
- package/error.js +6 -0
- package/error.js.map +1 -0
- package/error.mjs +2 -0
- package/error.mjs.map +1 -0
- package/index.d.mts +6 -0
- package/index.d.mts.map +1 -0
- package/index.d.ts +6 -0
- package/index.d.ts.map +1 -0
- package/index.js +30 -0
- package/index.js.map +1 -0
- package/index.mjs +7 -0
- package/index.mjs.map +1 -0
- package/internal/builtin-types.d.mts +73 -0
- package/internal/builtin-types.d.mts.map +1 -0
- package/internal/builtin-types.d.ts +73 -0
- package/internal/builtin-types.d.ts.map +1 -0
- package/internal/builtin-types.js +4 -0
- package/internal/builtin-types.js.map +1 -0
- package/internal/builtin-types.mjs +3 -0
- package/internal/builtin-types.mjs.map +1 -0
- package/internal/detect-platform.d.mts +15 -0
- package/internal/detect-platform.d.mts.map +1 -0
- package/internal/detect-platform.d.ts +15 -0
- package/internal/detect-platform.d.ts.map +1 -0
- package/internal/detect-platform.js +162 -0
- package/internal/detect-platform.js.map +1 -0
- package/internal/detect-platform.mjs +157 -0
- package/internal/detect-platform.mjs.map +1 -0
- package/internal/errors.d.mts +3 -0
- package/internal/errors.d.mts.map +1 -0
- package/internal/errors.d.ts +3 -0
- package/internal/errors.d.ts.map +1 -0
- package/internal/errors.js +41 -0
- package/internal/errors.js.map +1 -0
- package/internal/errors.mjs +36 -0
- package/internal/errors.mjs.map +1 -0
- package/internal/headers.d.mts +20 -0
- package/internal/headers.d.mts.map +1 -0
- package/internal/headers.d.ts +20 -0
- package/internal/headers.d.ts.map +1 -0
- package/internal/headers.js +79 -0
- package/internal/headers.js.map +1 -0
- package/internal/headers.mjs +74 -0
- package/internal/headers.mjs.map +1 -0
- package/internal/parse.d.mts +12 -0
- package/internal/parse.d.mts.map +1 -0
- package/internal/parse.d.ts +12 -0
- package/internal/parse.d.ts.map +1 -0
- package/internal/parse.js +40 -0
- package/internal/parse.js.map +1 -0
- package/internal/parse.mjs +37 -0
- package/internal/parse.mjs.map +1 -0
- package/internal/qs/formats.d.mts +7 -0
- package/internal/qs/formats.d.mts.map +1 -0
- package/internal/qs/formats.d.ts +7 -0
- package/internal/qs/formats.d.ts.map +1 -0
- package/internal/qs/formats.js +13 -0
- package/internal/qs/formats.js.map +1 -0
- package/internal/qs/formats.mjs +9 -0
- package/internal/qs/formats.mjs.map +1 -0
- package/internal/qs/index.d.mts +10 -0
- package/internal/qs/index.d.mts.map +1 -0
- package/internal/qs/index.d.ts +10 -0
- package/internal/qs/index.d.ts.map +1 -0
- package/internal/qs/index.js +14 -0
- package/internal/qs/index.js.map +1 -0
- package/internal/qs/index.mjs +10 -0
- package/internal/qs/index.mjs.map +1 -0
- package/internal/qs/stringify.d.mts +3 -0
- package/internal/qs/stringify.d.mts.map +1 -0
- package/internal/qs/stringify.d.ts +3 -0
- package/internal/qs/stringify.d.ts.map +1 -0
- package/internal/qs/stringify.js +277 -0
- package/internal/qs/stringify.js.map +1 -0
- package/internal/qs/stringify.mjs +274 -0
- package/internal/qs/stringify.mjs.map +1 -0
- package/internal/qs/types.d.mts +57 -0
- package/internal/qs/types.d.mts.map +1 -0
- package/internal/qs/types.d.ts +57 -0
- package/internal/qs/types.d.ts.map +1 -0
- package/internal/qs/types.js +3 -0
- package/internal/qs/types.js.map +1 -0
- package/internal/qs/types.mjs +2 -0
- package/internal/qs/types.mjs.map +1 -0
- package/internal/qs/utils.d.mts +15 -0
- package/internal/qs/utils.d.mts.map +1 -0
- package/internal/qs/utils.d.ts +15 -0
- package/internal/qs/utils.d.ts.map +1 -0
- package/internal/qs/utils.js +230 -0
- package/internal/qs/utils.js.map +1 -0
- package/internal/qs/utils.mjs +217 -0
- package/internal/qs/utils.mjs.map +1 -0
- package/internal/request-options.d.mts +75 -0
- package/internal/request-options.d.mts.map +1 -0
- package/internal/request-options.d.ts +75 -0
- package/internal/request-options.d.ts.map +1 -0
- package/internal/request-options.js +14 -0
- package/internal/request-options.js.map +1 -0
- package/internal/request-options.mjs +10 -0
- package/internal/request-options.mjs.map +1 -0
- package/internal/shim-types.d.mts +17 -0
- package/internal/shim-types.d.mts.map +1 -0
- package/internal/shim-types.d.ts +17 -0
- package/internal/shim-types.d.ts.map +1 -0
- package/internal/shim-types.js +4 -0
- package/internal/shim-types.js.map +1 -0
- package/internal/shim-types.mjs +3 -0
- package/internal/shim-types.mjs.map +1 -0
- package/internal/shims.d.mts +20 -0
- package/internal/shims.d.mts.map +1 -0
- package/internal/shims.d.ts +20 -0
- package/internal/shims.d.ts.map +1 -0
- package/internal/shims.js +92 -0
- package/internal/shims.js.map +1 -0
- package/internal/shims.mjs +85 -0
- package/internal/shims.mjs.map +1 -0
- package/internal/to-file.d.mts +45 -0
- package/internal/to-file.d.mts.map +1 -0
- package/internal/to-file.d.ts +45 -0
- package/internal/to-file.d.ts.map +1 -0
- package/internal/to-file.js +91 -0
- package/internal/to-file.js.map +1 -0
- package/internal/to-file.mjs +88 -0
- package/internal/to-file.mjs.map +1 -0
- package/internal/tslib.js +81 -0
- package/internal/tslib.mjs +17 -0
- package/internal/types.d.mts +69 -0
- package/internal/types.d.mts.map +1 -0
- package/internal/types.d.ts +69 -0
- package/internal/types.d.ts.map +1 -0
- package/internal/types.js +4 -0
- package/internal/types.js.map +1 -0
- package/internal/types.mjs +3 -0
- package/internal/types.mjs.map +1 -0
- package/internal/uploads.d.mts +42 -0
- package/internal/uploads.d.mts.map +1 -0
- package/internal/uploads.d.ts +42 -0
- package/internal/uploads.d.ts.map +1 -0
- package/internal/uploads.js +141 -0
- package/internal/uploads.js.map +1 -0
- package/internal/uploads.mjs +131 -0
- package/internal/uploads.mjs.map +1 -0
- package/internal/utils/base64.d.mts +3 -0
- package/internal/utils/base64.d.mts.map +1 -0
- package/internal/utils/base64.d.ts +3 -0
- package/internal/utils/base64.d.ts.map +1 -0
- package/internal/utils/base64.js +38 -0
- package/internal/utils/base64.js.map +1 -0
- package/internal/utils/base64.mjs +33 -0
- package/internal/utils/base64.mjs.map +1 -0
- package/internal/utils/bytes.d.mts +4 -0
- package/internal/utils/bytes.d.mts.map +1 -0
- package/internal/utils/bytes.d.ts +4 -0
- package/internal/utils/bytes.d.ts.map +1 -0
- package/internal/utils/bytes.js +31 -0
- package/internal/utils/bytes.js.map +1 -0
- package/internal/utils/bytes.mjs +26 -0
- package/internal/utils/bytes.mjs.map +1 -0
- package/internal/utils/env.d.mts +9 -0
- package/internal/utils/env.d.mts.map +1 -0
- package/internal/utils/env.d.ts +9 -0
- package/internal/utils/env.d.ts.map +1 -0
- package/internal/utils/env.js +22 -0
- package/internal/utils/env.js.map +1 -0
- package/internal/utils/env.mjs +18 -0
- package/internal/utils/env.mjs.map +1 -0
- package/internal/utils/log.d.mts +37 -0
- package/internal/utils/log.d.mts.map +1 -0
- package/internal/utils/log.d.ts +37 -0
- package/internal/utils/log.d.ts.map +1 -0
- package/internal/utils/log.js +87 -0
- package/internal/utils/log.js.map +1 -0
- package/internal/utils/log.mjs +81 -0
- package/internal/utils/log.mjs.map +1 -0
- package/internal/utils/path.d.mts +15 -0
- package/internal/utils/path.d.mts.map +1 -0
- package/internal/utils/path.d.ts +15 -0
- package/internal/utils/path.d.ts.map +1 -0
- package/internal/utils/path.js +79 -0
- package/internal/utils/path.js.map +1 -0
- package/internal/utils/path.mjs +74 -0
- package/internal/utils/path.mjs.map +1 -0
- package/internal/utils/query.d.mts +2 -0
- package/internal/utils/query.d.mts.map +1 -0
- package/internal/utils/query.d.ts +2 -0
- package/internal/utils/query.d.ts.map +1 -0
- package/internal/utils/query.js +10 -0
- package/internal/utils/query.js.map +1 -0
- package/internal/utils/query.mjs +6 -0
- package/internal/utils/query.mjs.map +1 -0
- package/internal/utils/sleep.d.mts +2 -0
- package/internal/utils/sleep.d.mts.map +1 -0
- package/internal/utils/sleep.d.ts +2 -0
- package/internal/utils/sleep.d.ts.map +1 -0
- package/internal/utils/sleep.js +7 -0
- package/internal/utils/sleep.js.map +1 -0
- package/internal/utils/sleep.mjs +3 -0
- package/internal/utils/sleep.mjs.map +1 -0
- package/internal/utils/uuid.d.mts +5 -0
- package/internal/utils/uuid.d.mts.map +1 -0
- package/internal/utils/uuid.d.ts +5 -0
- package/internal/utils/uuid.d.ts.map +1 -0
- package/internal/utils/uuid.js +19 -0
- package/internal/utils/uuid.js.map +1 -0
- package/internal/utils/uuid.mjs +15 -0
- package/internal/utils/uuid.mjs.map +1 -0
- package/internal/utils/values.d.mts +18 -0
- package/internal/utils/values.d.mts.map +1 -0
- package/internal/utils/values.d.ts +18 -0
- package/internal/utils/values.d.ts.map +1 -0
- package/internal/utils/values.js +112 -0
- package/internal/utils/values.js.map +1 -0
- package/internal/utils/values.mjs +94 -0
- package/internal/utils/values.mjs.map +1 -0
- package/internal/utils.d.mts +8 -0
- package/internal/utils.d.mts.map +1 -0
- package/internal/utils.d.ts +8 -0
- package/internal/utils.d.ts.map +1 -0
- package/internal/utils.js +12 -0
- package/internal/utils.js.map +1 -0
- package/internal/utils.mjs +9 -0
- package/internal/utils.mjs.map +1 -0
- package/lib/envelope.d.mts +4 -0
- package/lib/envelope.d.mts.map +1 -0
- package/lib/envelope.d.ts +4 -0
- package/lib/envelope.d.ts.map +1 -0
- package/lib/envelope.js +43 -0
- package/lib/envelope.js.map +1 -0
- package/lib/envelope.mjs +39 -0
- package/lib/envelope.mjs.map +1 -0
- package/package.json +142 -76
- package/resource.d.mts +2 -0
- package/resource.d.mts.map +1 -0
- package/resource.d.ts +2 -0
- package/resource.d.ts.map +1 -0
- package/resource.js +6 -0
- package/resource.js.map +1 -0
- package/resource.mjs +2 -0
- package/resource.mjs.map +1 -0
- package/resources/agents.d.mts +1392 -0
- package/resources/agents.d.mts.map +1 -0
- package/resources/agents.d.ts +1392 -0
- package/resources/agents.d.ts.map +1 -0
- package/resources/agents.js +192 -0
- package/resources/agents.js.map +1 -0
- package/resources/agents.mjs +188 -0
- package/resources/agents.mjs.map +1 -0
- package/resources/api-keys.d.mts +539 -0
- package/resources/api-keys.d.mts.map +1 -0
- package/resources/api-keys.d.ts +539 -0
- package/resources/api-keys.d.ts.map +1 -0
- package/resources/api-keys.js +100 -0
- package/resources/api-keys.js.map +1 -0
- package/resources/api-keys.mjs +96 -0
- package/resources/api-keys.mjs.map +1 -0
- package/resources/counterparties.d.mts +139 -0
- package/resources/counterparties.d.mts.map +1 -0
- package/resources/counterparties.d.ts +139 -0
- package/resources/counterparties.d.ts.map +1 -0
- package/resources/counterparties.js +32 -0
- package/resources/counterparties.js.map +1 -0
- package/resources/counterparties.mjs +28 -0
- package/resources/counterparties.mjs.map +1 -0
- package/resources/customers.d.mts +272 -0
- package/resources/customers.d.mts.map +1 -0
- package/resources/customers.d.ts +272 -0
- package/resources/customers.d.ts.map +1 -0
- package/resources/customers.js +48 -0
- package/resources/customers.js.map +1 -0
- package/resources/customers.mjs +44 -0
- package/resources/customers.mjs.map +1 -0
- package/resources/delegations.d.mts +458 -0
- package/resources/delegations.d.mts.map +1 -0
- package/resources/delegations.d.ts +458 -0
- package/resources/delegations.d.ts.map +1 -0
- package/resources/delegations.js +47 -0
- package/resources/delegations.js.map +1 -0
- package/resources/delegations.mjs +43 -0
- package/resources/delegations.mjs.map +1 -0
- package/resources/index.d.mts +12 -0
- package/resources/index.d.mts.map +1 -0
- package/resources/index.d.ts +12 -0
- package/resources/index.d.ts.map +1 -0
- package/resources/index.js +27 -0
- package/resources/index.js.map +1 -0
- package/resources/index.mjs +13 -0
- package/resources/index.mjs.map +1 -0
- package/resources/invitations.d.mts +304 -0
- package/resources/invitations.d.mts.map +1 -0
- package/resources/invitations.d.ts +304 -0
- package/resources/invitations.d.ts.map +1 -0
- package/resources/invitations.js +85 -0
- package/resources/invitations.js.map +1 -0
- package/resources/invitations.mjs +81 -0
- package/resources/invitations.mjs.map +1 -0
- package/resources/parties.d.mts +364 -0
- package/resources/parties.d.mts.map +1 -0
- package/resources/parties.d.ts +364 -0
- package/resources/parties.d.ts.map +1 -0
- package/resources/parties.js +78 -0
- package/resources/parties.js.map +1 -0
- package/resources/parties.mjs +74 -0
- package/resources/parties.mjs.map +1 -0
- package/resources/payment-requests.d.mts +442 -0
- package/resources/payment-requests.d.mts.map +1 -0
- package/resources/payment-requests.d.ts +442 -0
- package/resources/payment-requests.d.ts.map +1 -0
- package/resources/payment-requests.js +87 -0
- package/resources/payment-requests.js.map +1 -0
- package/resources/payment-requests.mjs +83 -0
- package/resources/payment-requests.mjs.map +1 -0
- package/resources/payments.d.mts +174 -0
- package/resources/payments.d.mts.map +1 -0
- package/resources/payments.d.ts +174 -0
- package/resources/payments.d.ts.map +1 -0
- package/resources/payments.js +40 -0
- package/resources/payments.js.map +1 -0
- package/resources/payments.mjs +36 -0
- package/resources/payments.mjs.map +1 -0
- package/resources/transactions.d.mts +478 -0
- package/resources/transactions.d.mts.map +1 -0
- package/resources/transactions.d.ts +478 -0
- package/resources/transactions.d.ts.map +1 -0
- package/resources/transactions.js +48 -0
- package/resources/transactions.js.map +1 -0
- package/resources/transactions.mjs +44 -0
- package/resources/transactions.mjs.map +1 -0
- package/resources/wallet.d.mts +628 -0
- package/resources/wallet.d.mts.map +1 -0
- package/resources/wallet.d.ts +628 -0
- package/resources/wallet.d.ts.map +1 -0
- package/resources/wallet.js +161 -0
- package/resources/wallet.js.map +1 -0
- package/resources/wallet.mjs +157 -0
- package/resources/wallet.mjs.map +1 -0
- package/resources.d.mts +2 -0
- package/resources.d.mts.map +1 -0
- package/resources.d.ts +2 -0
- package/resources.d.ts.map +1 -0
- package/resources.js +5 -0
- package/resources.js.map +1 -0
- package/resources.mjs +2 -0
- package/resources.mjs.map +1 -0
- package/src/api-promise.ts +2 -0
- package/src/client.ts +1020 -0
- package/src/core/README.md +3 -0
- package/src/core/api-promise.ts +92 -0
- package/src/core/error.ts +130 -0
- package/src/core/resource.ts +11 -0
- package/src/core/uploads.ts +2 -0
- package/src/error.ts +2 -0
- package/src/index.ts +22 -0
- package/src/internal/README.md +3 -0
- package/src/internal/builtin-types.ts +93 -0
- package/src/internal/detect-platform.ts +196 -0
- package/src/internal/errors.ts +33 -0
- package/src/internal/headers.ts +97 -0
- package/src/internal/parse.ts +56 -0
- package/src/internal/qs/LICENSE.md +13 -0
- package/src/internal/qs/README.md +3 -0
- package/src/internal/qs/formats.ts +10 -0
- package/src/internal/qs/index.ts +13 -0
- package/src/internal/qs/stringify.ts +385 -0
- package/src/internal/qs/types.ts +71 -0
- package/src/internal/qs/utils.ts +265 -0
- package/src/internal/request-options.ts +91 -0
- package/src/internal/shim-types.ts +26 -0
- package/src/internal/shims.ts +107 -0
- package/src/internal/to-file.ts +154 -0
- package/src/internal/types.ts +93 -0
- package/src/internal/uploads.ts +187 -0
- package/src/internal/utils/base64.ts +40 -0
- package/src/internal/utils/bytes.ts +32 -0
- package/src/internal/utils/env.ts +18 -0
- package/src/internal/utils/log.ts +128 -0
- package/src/internal/utils/path.ts +88 -0
- package/src/internal/utils/query.ts +7 -0
- package/src/internal/utils/sleep.ts +3 -0
- package/src/internal/utils/uuid.ts +17 -0
- package/src/internal/utils/values.ts +105 -0
- package/src/internal/utils.ts +9 -0
- package/src/lib/.keep +4 -0
- package/src/lib/envelope.ts +32 -0
- package/src/resource.ts +2 -0
- package/src/resources/agents.ts +1785 -0
- package/src/resources/api-keys.ts +743 -0
- package/src/resources/counterparties.ts +187 -0
- package/src/resources/customers.ts +365 -0
- package/src/resources/delegations.ts +580 -0
- package/src/resources/index.ts +95 -0
- package/src/resources/invitations.ts +414 -0
- package/src/resources/parties.ts +493 -0
- package/src/resources/payment-requests.ts +601 -0
- package/src/resources/payments.ts +228 -0
- package/src/resources/transactions.ts +610 -0
- package/src/resources/wallet.ts +864 -0
- package/src/resources.ts +1 -0
- package/src/tsconfig.json +11 -0
- package/src/uploads.ts +2 -0
- package/src/version.ts +1 -0
- package/uploads.d.mts +2 -0
- package/uploads.d.mts.map +1 -0
- package/uploads.d.ts +2 -0
- package/uploads.d.ts.map +1 -0
- package/uploads.js +6 -0
- package/uploads.js.map +1 -0
- package/uploads.mjs +2 -0
- package/uploads.mjs.map +1 -0
- package/version.d.mts +2 -0
- package/version.d.mts.map +1 -0
- package/version.d.ts +2 -0
- package/version.d.ts.map +1 -0
- package/version.js +5 -0
- package/version.js.map +1 -0
- package/version.mjs +2 -0
- package/version.mjs.map +1 -0
- package/dist/index.cjs +0 -1688
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -879
- package/dist/index.d.ts +0 -879
- package/dist/index.js +0 -1657
- package/dist/index.js.map +0 -1
- package/dist/mcp/cli.cjs +0 -166
- package/dist/mcp/cli.cjs.map +0 -1
- package/dist/mcp/cli.d.cts +0 -1
- package/dist/mcp/cli.d.ts +0 -1
- package/dist/mcp/cli.js +0 -164
- package/dist/mcp/cli.js.map +0 -1
- package/dist/mcp/index.cjs +0 -8
- package/dist/mcp/index.cjs.map +0 -1
- package/dist/mcp/index.d.cts +0 -9
- package/dist/mcp/index.d.ts +0 -9
- package/dist/mcp/index.js +0 -6
- package/dist/mcp/index.js.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,1657 +0,0 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'async_hooks';
|
|
2
|
-
import { createHash, randomUUID, createHmac, timingSafeEqual } from 'crypto';
|
|
3
|
-
|
|
4
|
-
// src/errors.ts
|
|
5
|
-
var NaturalError = class extends Error {
|
|
6
|
-
statusCode;
|
|
7
|
-
code;
|
|
8
|
-
constructor(message, options) {
|
|
9
|
-
super(message);
|
|
10
|
-
this.name = "NaturalError";
|
|
11
|
-
this.statusCode = options?.statusCode;
|
|
12
|
-
this.code = options?.code;
|
|
13
|
-
if (Error.captureStackTrace) {
|
|
14
|
-
Error.captureStackTrace(this, this.constructor);
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
var AuthenticationError = class extends NaturalError {
|
|
19
|
-
constructor(message = "Invalid or missing API key") {
|
|
20
|
-
super(message, { statusCode: 401, code: "authentication_error" });
|
|
21
|
-
this.name = "AuthenticationError";
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
var InvalidRequestError = class extends NaturalError {
|
|
25
|
-
constructor(message, code = "invalid_request") {
|
|
26
|
-
super(message, { statusCode: 400, code });
|
|
27
|
-
this.name = "InvalidRequestError";
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
var PaymentError = class extends NaturalError {
|
|
31
|
-
constructor(message, code = "payment_error") {
|
|
32
|
-
super(message, { statusCode: 400, code });
|
|
33
|
-
this.name = "PaymentError";
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
var InsufficientFundsError = class extends PaymentError {
|
|
37
|
-
constructor(message = "Insufficient funds") {
|
|
38
|
-
super(message, "insufficient_funds");
|
|
39
|
-
this.name = "InsufficientFundsError";
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
var RecipientNotFoundError = class extends PaymentError {
|
|
43
|
-
constructor(message = "Recipient not found") {
|
|
44
|
-
super(message, "recipient_not_found");
|
|
45
|
-
this.name = "RecipientNotFoundError";
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
var RateLimitError = class extends NaturalError {
|
|
49
|
-
retryAfter;
|
|
50
|
-
constructor(message = "Rate limit exceeded", retryAfter) {
|
|
51
|
-
super(message, { statusCode: 429, code: "rate_limit_exceeded" });
|
|
52
|
-
this.name = "RateLimitError";
|
|
53
|
-
this.retryAfter = retryAfter;
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
var ServerError = class extends NaturalError {
|
|
57
|
-
constructor(message = "Internal server error") {
|
|
58
|
-
super(message, { statusCode: 500, code: "server_error" });
|
|
59
|
-
this.name = "ServerError";
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
var WebhookVerificationError = class extends NaturalError {
|
|
63
|
-
constructor(message) {
|
|
64
|
-
super(message, { code: "webhook_verification_failed" });
|
|
65
|
-
this.name = "WebhookVerificationError";
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
// src/version.ts
|
|
70
|
-
var VERSION = "0.1.4";
|
|
71
|
-
|
|
72
|
-
// src/logging.ts
|
|
73
|
-
var LOG_LEVEL_VALUES = {
|
|
74
|
-
debug: 10,
|
|
75
|
-
info: 20,
|
|
76
|
-
warning: 30,
|
|
77
|
-
error: 40
|
|
78
|
-
};
|
|
79
|
-
var asyncContext = new AsyncLocalStorage();
|
|
80
|
-
var globalContext = {};
|
|
81
|
-
function getContext() {
|
|
82
|
-
const asyncStore = asyncContext.getStore();
|
|
83
|
-
if (asyncStore) {
|
|
84
|
-
return { ...asyncStore };
|
|
85
|
-
}
|
|
86
|
-
return { ...globalContext };
|
|
87
|
-
}
|
|
88
|
-
function sanitizeString(value) {
|
|
89
|
-
let sanitized = "";
|
|
90
|
-
for (const char of value) {
|
|
91
|
-
if (char === "\r" || char === "\n") {
|
|
92
|
-
sanitized += "\\n";
|
|
93
|
-
} else if (char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) {
|
|
94
|
-
sanitized += `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`;
|
|
95
|
-
} else {
|
|
96
|
-
sanitized += char;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
const maxLength = 1e3;
|
|
100
|
-
if (sanitized.length > maxLength) {
|
|
101
|
-
sanitized = sanitized.slice(0, maxLength) + "...[truncated]";
|
|
102
|
-
}
|
|
103
|
-
return sanitized;
|
|
104
|
-
}
|
|
105
|
-
function sanitizeLogValue(value, depth = 0) {
|
|
106
|
-
const maxDepth = 10;
|
|
107
|
-
if (depth > maxDepth) {
|
|
108
|
-
return "[max depth exceeded]";
|
|
109
|
-
}
|
|
110
|
-
if (value === null || value === void 0) {
|
|
111
|
-
return value;
|
|
112
|
-
}
|
|
113
|
-
if (typeof value === "string") {
|
|
114
|
-
return sanitizeString(value);
|
|
115
|
-
}
|
|
116
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
117
|
-
return value;
|
|
118
|
-
}
|
|
119
|
-
if (Array.isArray(value)) {
|
|
120
|
-
return value.map((item) => sanitizeLogValue(item, depth + 1));
|
|
121
|
-
}
|
|
122
|
-
if (typeof value === "object") {
|
|
123
|
-
const sanitized = {};
|
|
124
|
-
for (const [key, val] of Object.entries(value)) {
|
|
125
|
-
const sanitizedKey = sanitizeString(key);
|
|
126
|
-
sanitized[sanitizedKey] = sanitizeLogValue(val, depth + 1);
|
|
127
|
-
}
|
|
128
|
-
return sanitized;
|
|
129
|
-
}
|
|
130
|
-
return `[${typeof value}]`;
|
|
131
|
-
}
|
|
132
|
-
function bindContext(context) {
|
|
133
|
-
const sanitized = {};
|
|
134
|
-
for (const [key, value] of Object.entries(context)) {
|
|
135
|
-
sanitized[key] = sanitizeLogValue(value);
|
|
136
|
-
}
|
|
137
|
-
const asyncStore = asyncContext.getStore();
|
|
138
|
-
if (asyncStore) {
|
|
139
|
-
Object.assign(asyncStore, sanitized);
|
|
140
|
-
}
|
|
141
|
-
globalContext = { ...globalContext, ...sanitized };
|
|
142
|
-
}
|
|
143
|
-
function clearContext() {
|
|
144
|
-
const asyncStore = asyncContext.getStore();
|
|
145
|
-
if (asyncStore) {
|
|
146
|
-
for (const key of Object.keys(asyncStore)) {
|
|
147
|
-
delete asyncStore[key];
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
globalContext = {};
|
|
151
|
-
}
|
|
152
|
-
function runWithContext(context, fn) {
|
|
153
|
-
const sanitized = {};
|
|
154
|
-
for (const [key, value] of Object.entries(context)) {
|
|
155
|
-
sanitized[key] = sanitizeLogValue(value);
|
|
156
|
-
}
|
|
157
|
-
return asyncContext.run(sanitized, fn);
|
|
158
|
-
}
|
|
159
|
-
var loggingConfig = {
|
|
160
|
-
level: process.env["NATURAL_LOG_LEVEL"]?.toLowerCase() || "info",
|
|
161
|
-
jsonFormat: process.env["NATURAL_LOG_FORMAT"]?.toLowerCase() === "json",
|
|
162
|
-
serviceName: "naturalpay-sdk",
|
|
163
|
-
environment: process.env["NATURAL_ENV"] || process.env["DD_ENV"] || "development"
|
|
164
|
-
};
|
|
165
|
-
function configureLogging(options) {
|
|
166
|
-
if (options?.level) {
|
|
167
|
-
loggingConfig.level = options.level;
|
|
168
|
-
}
|
|
169
|
-
if (options?.jsonFormat !== void 0) {
|
|
170
|
-
loggingConfig.jsonFormat = options.jsonFormat;
|
|
171
|
-
}
|
|
172
|
-
if (options?.serviceName) {
|
|
173
|
-
loggingConfig.serviceName = options.serviceName;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
function getSourceInfo() {
|
|
177
|
-
const stack = new Error().stack;
|
|
178
|
-
if (!stack) {
|
|
179
|
-
return { file: "unknown", line: 0, function: "unknown" };
|
|
180
|
-
}
|
|
181
|
-
const lines = stack.split("\n");
|
|
182
|
-
const callerLine = lines[4] || lines[3] || "";
|
|
183
|
-
const match = callerLine.match(/at\s+(?:(.+?)\s+\()?(.*?):(\d+):\d+\)?/);
|
|
184
|
-
if (match) {
|
|
185
|
-
return {
|
|
186
|
-
function: match[1] || "anonymous",
|
|
187
|
-
file: match[2] || "unknown",
|
|
188
|
-
line: parseInt(match[3] || "0", 10)
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
return { file: "unknown", line: 0, function: "unknown" };
|
|
192
|
-
}
|
|
193
|
-
function formatJsonLog(level, loggerName, message, extra) {
|
|
194
|
-
const record = {
|
|
195
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
196
|
-
level: level.toUpperCase(),
|
|
197
|
-
logger: loggerName,
|
|
198
|
-
message,
|
|
199
|
-
source: getSourceInfo(),
|
|
200
|
-
service: loggingConfig.serviceName,
|
|
201
|
-
environment: loggingConfig.environment,
|
|
202
|
-
version: VERSION,
|
|
203
|
-
...getContext(),
|
|
204
|
-
...extra
|
|
205
|
-
};
|
|
206
|
-
const ddTraceId = process.env["DD_TRACE_ID"];
|
|
207
|
-
const ddSpanId = process.env["DD_SPAN_ID"];
|
|
208
|
-
if (ddTraceId) {
|
|
209
|
-
record["dd.trace_id"] = ddTraceId;
|
|
210
|
-
record["dd.span_id"] = ddSpanId;
|
|
211
|
-
record["dd.service"] = loggingConfig.serviceName;
|
|
212
|
-
record["dd.version"] = VERSION;
|
|
213
|
-
record["dd.env"] = loggingConfig.environment;
|
|
214
|
-
}
|
|
215
|
-
return JSON.stringify(record);
|
|
216
|
-
}
|
|
217
|
-
function formatTextLog(level, loggerName, message, extra) {
|
|
218
|
-
const contextEntries = Object.entries({ ...getContext(), ...extra });
|
|
219
|
-
const contextStr = contextEntries.length > 0 ? ` [${contextEntries.map(([k, v]) => `${k}=${v}`).join(", ")}]` : "";
|
|
220
|
-
return `${level.toUpperCase().padEnd(8)} ${loggerName}: ${message}${contextStr}`;
|
|
221
|
-
}
|
|
222
|
-
var Logger = class {
|
|
223
|
-
constructor(name) {
|
|
224
|
-
this.name = name;
|
|
225
|
-
}
|
|
226
|
-
log(level, message, extra) {
|
|
227
|
-
if (LOG_LEVEL_VALUES[level] < LOG_LEVEL_VALUES[loggingConfig.level]) {
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
const formatted = loggingConfig.jsonFormat ? formatJsonLog(level, this.name, message, extra) : formatTextLog(level, this.name, message, extra);
|
|
231
|
-
if (level === "error") {
|
|
232
|
-
console.error(formatted);
|
|
233
|
-
} else if (level === "warning") {
|
|
234
|
-
console.warn(formatted);
|
|
235
|
-
} else {
|
|
236
|
-
console.error(formatted);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
debug(message, extra) {
|
|
240
|
-
this.log("debug", message, extra);
|
|
241
|
-
}
|
|
242
|
-
info(message, extra) {
|
|
243
|
-
this.log("info", message, extra);
|
|
244
|
-
}
|
|
245
|
-
warning(message, extra) {
|
|
246
|
-
this.log("warning", message, extra);
|
|
247
|
-
}
|
|
248
|
-
warn(message, extra) {
|
|
249
|
-
this.warning(message, extra);
|
|
250
|
-
}
|
|
251
|
-
error(message, extra) {
|
|
252
|
-
this.log("error", message, extra);
|
|
253
|
-
}
|
|
254
|
-
};
|
|
255
|
-
function getLogger(name) {
|
|
256
|
-
if (!name.startsWith("naturalpay")) {
|
|
257
|
-
name = `naturalpay.${name}`;
|
|
258
|
-
}
|
|
259
|
-
return new Logger(name);
|
|
260
|
-
}
|
|
261
|
-
function logError(logger3, message, options) {
|
|
262
|
-
const extra = { ...options };
|
|
263
|
-
if (options?.error) {
|
|
264
|
-
extra["errorType"] = options.error.name;
|
|
265
|
-
extra["errorMessage"] = options.error.message;
|
|
266
|
-
if (options.error.stack) {
|
|
267
|
-
extra["errorStack"] = options.error.stack.split("\n").slice(0, 5).join("\n");
|
|
268
|
-
}
|
|
269
|
-
delete extra["error"];
|
|
270
|
-
}
|
|
271
|
-
logger3.error(message, extra);
|
|
272
|
-
}
|
|
273
|
-
function logApiCall(logger3, method, path, options) {
|
|
274
|
-
const extra = {
|
|
275
|
-
method,
|
|
276
|
-
path,
|
|
277
|
-
...options
|
|
278
|
-
};
|
|
279
|
-
if (options?.statusCode) {
|
|
280
|
-
extra["statusCode"] = options.statusCode;
|
|
281
|
-
}
|
|
282
|
-
if (options?.durationMs !== void 0) {
|
|
283
|
-
extra["durationMs"] = Math.round(options.durationMs * 100) / 100;
|
|
284
|
-
}
|
|
285
|
-
if (options?.error) {
|
|
286
|
-
logError(logger3, `API call failed: ${method} ${path}`, extra);
|
|
287
|
-
} else if (options?.statusCode && options.statusCode >= 400) {
|
|
288
|
-
logger3.warning(`API call error: ${method} ${path} -> ${options.statusCode}`, extra);
|
|
289
|
-
} else {
|
|
290
|
-
logger3.info(`API call: ${method} ${path} -> ${options?.statusCode}`, extra);
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
function logToolCall(logger3, toolName, options) {
|
|
294
|
-
const extra = {
|
|
295
|
-
toolName,
|
|
296
|
-
...options
|
|
297
|
-
};
|
|
298
|
-
if (options?.durationMs !== void 0) {
|
|
299
|
-
extra["durationMs"] = Math.round(options.durationMs * 100) / 100;
|
|
300
|
-
}
|
|
301
|
-
if (options?.error) {
|
|
302
|
-
logError(logger3, `Tool call failed: ${toolName}`, extra);
|
|
303
|
-
} else if (options?.success === false) {
|
|
304
|
-
logger3.warning(`Tool call returned error: ${toolName}`, extra);
|
|
305
|
-
} else {
|
|
306
|
-
logger3.info(`Tool call: ${toolName}`, extra);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
function configHash(cfg) {
|
|
310
|
-
const content = JSON.stringify({
|
|
311
|
-
system_prompt: cfg.systemPrompt,
|
|
312
|
-
tools_available: [...cfg.toolsAvailable].sort()
|
|
313
|
-
});
|
|
314
|
-
return createHash("sha256").update(content).digest("hex");
|
|
315
|
-
}
|
|
316
|
-
function agentConfigToDict(cfg) {
|
|
317
|
-
return {
|
|
318
|
-
system_prompt: cfg.systemPrompt,
|
|
319
|
-
tools_available: [...cfg.toolsAvailable].sort()
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
function modelUsageToDict(usage) {
|
|
323
|
-
const dict = {};
|
|
324
|
-
if (usage.model) {
|
|
325
|
-
dict.model = usage.model;
|
|
326
|
-
}
|
|
327
|
-
if (usage.provider) {
|
|
328
|
-
dict.provider = usage.provider;
|
|
329
|
-
}
|
|
330
|
-
if (usage.inputTokens != null) {
|
|
331
|
-
dict.input_tokens = usage.inputTokens;
|
|
332
|
-
}
|
|
333
|
-
if (usage.outputTokens != null) {
|
|
334
|
-
dict.output_tokens = usage.outputTokens;
|
|
335
|
-
}
|
|
336
|
-
if (usage.toolsCalled != null && usage.toolsCalled.length > 0) {
|
|
337
|
-
dict.tools_called = usage.toolsCalled;
|
|
338
|
-
}
|
|
339
|
-
return dict;
|
|
340
|
-
}
|
|
341
|
-
var logger = getLogger("tool-call-context");
|
|
342
|
-
var toolCallStorage = new AsyncLocalStorage();
|
|
343
|
-
function generateToolCallId() {
|
|
344
|
-
return `tc_${randomUUID()}`;
|
|
345
|
-
}
|
|
346
|
-
function getToolCallHeader() {
|
|
347
|
-
const data = toolCallStorage.getStore();
|
|
348
|
-
if (!data) return void 0;
|
|
349
|
-
const full = Buffer.from(JSON.stringify(data)).toString("base64");
|
|
350
|
-
if (full.length <= 16 * 1024) return full;
|
|
351
|
-
logger.warning("Tool call header exceeds 16KB, omitting arguments", {
|
|
352
|
-
toolCallId: data.tool_call_id,
|
|
353
|
-
toolName: data.tool_name,
|
|
354
|
-
fullSizeBytes: full.length
|
|
355
|
-
});
|
|
356
|
-
const slim = {
|
|
357
|
-
tool_call_id: data.tool_call_id,
|
|
358
|
-
tool_name: data.tool_name
|
|
359
|
-
};
|
|
360
|
-
return Buffer.from(JSON.stringify(slim)).toString("base64");
|
|
361
|
-
}
|
|
362
|
-
function runWithToolCall(toolCallId, name, args, fn) {
|
|
363
|
-
return toolCallStorage.run(
|
|
364
|
-
{
|
|
365
|
-
tool_call_id: toolCallId,
|
|
366
|
-
tool_name: name,
|
|
367
|
-
tool_call_arguments: JSON.stringify(args)
|
|
368
|
-
},
|
|
369
|
-
fn
|
|
370
|
-
);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
// src/http.ts
|
|
374
|
-
var logger2 = getLogger("http");
|
|
375
|
-
var DEFAULT_BASE_URL = "https://api.natural.co";
|
|
376
|
-
var DEFAULT_TIMEOUT = 3e4;
|
|
377
|
-
var API_KEY_PREFIX_REGEX = /^sk_ntl_(dev|sandbox|prod)_/;
|
|
378
|
-
function parseApiKeyEnv(key) {
|
|
379
|
-
const match = API_KEY_PREFIX_REGEX.exec(key);
|
|
380
|
-
if (match) {
|
|
381
|
-
return match[1];
|
|
382
|
-
}
|
|
383
|
-
const preview = key.length > 16 ? `${key.slice(0, 16)}...` : key;
|
|
384
|
-
throw new InvalidRequestError(
|
|
385
|
-
`Invalid API key prefix. Expected a key starting with 'sk_ntl_dev_', 'sk_ntl_sandbox_', or 'sk_ntl_prod_'. Got: '${preview}'`
|
|
386
|
-
);
|
|
387
|
-
}
|
|
388
|
-
function validateBaseUrl(baseUrl) {
|
|
389
|
-
let url;
|
|
390
|
-
try {
|
|
391
|
-
url = new URL(baseUrl);
|
|
392
|
-
} catch {
|
|
393
|
-
throw new InvalidRequestError(`Invalid baseUrl: '${baseUrl}'. Must be a valid absolute URL.`);
|
|
394
|
-
}
|
|
395
|
-
if (url.protocol === "https:") {
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
const host = url.hostname;
|
|
399
|
-
if (host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]") {
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
const allowHttp = process.env["NATURAL_ALLOW_HTTP"];
|
|
403
|
-
if (allowHttp && allowHttp !== "0" && allowHttp.toLowerCase() !== "false") {
|
|
404
|
-
return;
|
|
405
|
-
}
|
|
406
|
-
throw new InvalidRequestError(
|
|
407
|
-
`baseUrl must use HTTPS (got '${baseUrl}'). To allow plaintext HTTP for development, set NATURAL_ALLOW_HTTP=1 or use a localhost host.`
|
|
408
|
-
);
|
|
409
|
-
}
|
|
410
|
-
function hashString(str) {
|
|
411
|
-
let hash = 0;
|
|
412
|
-
for (let i = 0; i < str.length; i++) {
|
|
413
|
-
const char = str.charCodeAt(i);
|
|
414
|
-
hash = (hash << 5) - hash + char;
|
|
415
|
-
hash = hash & hash;
|
|
416
|
-
}
|
|
417
|
-
return Math.abs(hash).toString(16).slice(0, 16);
|
|
418
|
-
}
|
|
419
|
-
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
420
|
-
function hasIdempotencyKey(headers) {
|
|
421
|
-
return Object.entries(headers).some(
|
|
422
|
-
([k, v]) => k.toLowerCase() === "idempotency-key" && v !== ""
|
|
423
|
-
);
|
|
424
|
-
}
|
|
425
|
-
function shouldRetry(method, headers, error, attempt, maxRetries) {
|
|
426
|
-
if (attempt >= maxRetries) return false;
|
|
427
|
-
if (error instanceof AuthenticationError) return false;
|
|
428
|
-
if (error instanceof InvalidRequestError) return false;
|
|
429
|
-
if (!(error instanceof RateLimitError) && error instanceof NaturalError && error.statusCode && error.statusCode >= 400 && error.statusCode < 500) {
|
|
430
|
-
return false;
|
|
431
|
-
}
|
|
432
|
-
const isRetryable = error instanceof ServerError || error instanceof RateLimitError || error instanceof NaturalError && !(error instanceof AuthenticationError);
|
|
433
|
-
if (!isRetryable) return false;
|
|
434
|
-
if (SAFE_METHODS.has(method.toUpperCase())) return true;
|
|
435
|
-
return hasIdempotencyKey(headers);
|
|
436
|
-
}
|
|
437
|
-
var MAX_RETRY_AFTER_MS = 6e4;
|
|
438
|
-
function calculateRetryDelay(attempt, retryAfterSeconds) {
|
|
439
|
-
if (retryAfterSeconds != null && Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0) {
|
|
440
|
-
return Math.min(retryAfterSeconds * 1e3, MAX_RETRY_AFTER_MS);
|
|
441
|
-
}
|
|
442
|
-
const jitter = 1 + Math.random() * 0.25;
|
|
443
|
-
return Math.min(500 * Math.pow(2, attempt) * jitter, 5e3);
|
|
444
|
-
}
|
|
445
|
-
var HTTPClient = class _HTTPClient {
|
|
446
|
-
apiKey;
|
|
447
|
-
baseUrl;
|
|
448
|
-
timeout;
|
|
449
|
-
maxRetries;
|
|
450
|
-
jwtCache = /* @__PURE__ */ new Map();
|
|
451
|
-
agentConfig;
|
|
452
|
-
_defaultModelUsage;
|
|
453
|
-
_configResolved = false;
|
|
454
|
-
_configAttempted = false;
|
|
455
|
-
_registerConfigPromise = null;
|
|
456
|
-
_nextRetryAt = 0;
|
|
457
|
-
_retryBackoffMs = 1e3;
|
|
458
|
-
static MAX_RETRY_BACKOFF_MS = 5 * 60 * 1e3;
|
|
459
|
-
constructor(options = {}) {
|
|
460
|
-
this.apiKey = options.apiKey ?? process.env["NATURAL_API_KEY"] ?? "";
|
|
461
|
-
this.baseUrl = (options.baseUrl ?? process.env["NATURAL_SERVER_URL"] ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
462
|
-
validateBaseUrl(this.baseUrl);
|
|
463
|
-
if (this.apiKey) {
|
|
464
|
-
parseApiKeyEnv(this.apiKey);
|
|
465
|
-
}
|
|
466
|
-
this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
467
|
-
this.agentConfig = options.agentConfig ? {
|
|
468
|
-
systemPrompt: options.agentConfig.systemPrompt,
|
|
469
|
-
toolsAvailable: [...options.agentConfig.toolsAvailable]
|
|
470
|
-
} : void 0;
|
|
471
|
-
if (options.defaultModelUsage) {
|
|
472
|
-
this._defaultModelUsage = {
|
|
473
|
-
model: options.defaultModelUsage.model,
|
|
474
|
-
provider: options.defaultModelUsage.provider
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
const maxRetries = options.maxRetries ?? 2;
|
|
478
|
-
if (!Number.isInteger(maxRetries) || maxRetries < 0) {
|
|
479
|
-
throw new InvalidRequestError("maxRetries must be a non-negative integer");
|
|
480
|
-
}
|
|
481
|
-
this.maxRetries = maxRetries;
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Get a cached JWT or exchange API key for a new one.
|
|
485
|
-
* Retries on transient failures (5xx, network) but not on 401.
|
|
486
|
-
*/
|
|
487
|
-
async getJwt() {
|
|
488
|
-
if (!this.apiKey) {
|
|
489
|
-
throw new AuthenticationError();
|
|
490
|
-
}
|
|
491
|
-
const cacheKey = hashString(this.apiKey);
|
|
492
|
-
const cached = this.jwtCache.get(cacheKey);
|
|
493
|
-
if (cached && Date.now() < cached.expiresAt) {
|
|
494
|
-
return cached.token;
|
|
495
|
-
}
|
|
496
|
-
logger2.debug("Exchanging API key for JWT", { path: "/auth/api/token" });
|
|
497
|
-
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
498
|
-
const controller = new AbortController();
|
|
499
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
500
|
-
try {
|
|
501
|
-
const response = await fetch(`${this.baseUrl}/auth/api/token`, {
|
|
502
|
-
method: "POST",
|
|
503
|
-
headers: {
|
|
504
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
505
|
-
"Content-Type": "application/json"
|
|
506
|
-
},
|
|
507
|
-
signal: controller.signal
|
|
508
|
-
});
|
|
509
|
-
clearTimeout(timeoutId);
|
|
510
|
-
if (response.status === 429) {
|
|
511
|
-
const retryAfter = response.headers.get("Retry-After");
|
|
512
|
-
const rateError = new RateLimitError(
|
|
513
|
-
"JWT exchange rate limited",
|
|
514
|
-
retryAfter ? parseInt(retryAfter, 10) : void 0
|
|
515
|
-
);
|
|
516
|
-
throw rateError;
|
|
517
|
-
}
|
|
518
|
-
if (response.status >= 400 && response.status < 500) {
|
|
519
|
-
const authError = new AuthenticationError(
|
|
520
|
-
`Authentication failed (status=${response.status})`
|
|
521
|
-
);
|
|
522
|
-
logError(logger2, "JWT exchange failed", {
|
|
523
|
-
error: authError,
|
|
524
|
-
statusCode: response.status,
|
|
525
|
-
path: "/auth/api/token"
|
|
526
|
-
});
|
|
527
|
-
throw authError;
|
|
528
|
-
}
|
|
529
|
-
if (response.status >= 500) {
|
|
530
|
-
const serverError = new ServerError(`JWT exchange failed (status=${response.status})`);
|
|
531
|
-
logError(logger2, "JWT exchange server error", {
|
|
532
|
-
error: serverError,
|
|
533
|
-
statusCode: response.status,
|
|
534
|
-
path: "/auth/api/token"
|
|
535
|
-
});
|
|
536
|
-
throw serverError;
|
|
537
|
-
}
|
|
538
|
-
const data = await response.json();
|
|
539
|
-
const expiresIn = data.expiresIn ?? 900;
|
|
540
|
-
const expiresAt = Date.now() + (expiresIn - 30) * 1e3;
|
|
541
|
-
this.jwtCache.set(cacheKey, { token: data.accessToken, expiresAt });
|
|
542
|
-
return data.accessToken;
|
|
543
|
-
} catch (error) {
|
|
544
|
-
clearTimeout(timeoutId);
|
|
545
|
-
if (error instanceof AuthenticationError) {
|
|
546
|
-
throw error;
|
|
547
|
-
}
|
|
548
|
-
let sdkError;
|
|
549
|
-
if (error instanceof NaturalError) {
|
|
550
|
-
sdkError = error;
|
|
551
|
-
} else if (error instanceof Error && error.name === "AbortError") {
|
|
552
|
-
sdkError = new NaturalError("Request timed out during authentication");
|
|
553
|
-
} else {
|
|
554
|
-
sdkError = new NaturalError(
|
|
555
|
-
`Network error during authentication: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
556
|
-
);
|
|
557
|
-
}
|
|
558
|
-
if (attempt < this.maxRetries) {
|
|
559
|
-
const retryAfter = sdkError instanceof RateLimitError ? sdkError.retryAfter : void 0;
|
|
560
|
-
const delay = calculateRetryDelay(attempt, retryAfter);
|
|
561
|
-
const reason = sdkError instanceof RateLimitError ? "429 rate limited" : sdkError instanceof ServerError ? `status ${sdkError.statusCode}` : "network error";
|
|
562
|
-
logger2.warning(`Retrying JWT exchange (attempt ${attempt + 1}/${this.maxRetries})`, {
|
|
563
|
-
path: "/auth/api/token",
|
|
564
|
-
attempt: attempt + 1,
|
|
565
|
-
maxRetries: this.maxRetries,
|
|
566
|
-
delayMs: Math.round(delay),
|
|
567
|
-
reason
|
|
568
|
-
});
|
|
569
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
570
|
-
continue;
|
|
571
|
-
}
|
|
572
|
-
logError(logger2, "JWT exchange failed after retries", {
|
|
573
|
-
error: sdkError,
|
|
574
|
-
path: "/auth/api/token"
|
|
575
|
-
});
|
|
576
|
-
throw sdkError;
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
throw new NaturalError("Unexpected retry exhaustion during JWT exchange");
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* Build URL with query parameters.
|
|
583
|
-
*/
|
|
584
|
-
buildUrl(path, params) {
|
|
585
|
-
const url = new URL(path, this.baseUrl);
|
|
586
|
-
if (params) {
|
|
587
|
-
for (const [key, value] of Object.entries(params)) {
|
|
588
|
-
if (value !== void 0 && value !== null) {
|
|
589
|
-
url.searchParams.set(key, String(value));
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
return url.toString();
|
|
594
|
-
}
|
|
595
|
-
/**
|
|
596
|
-
* Handle API response and throw appropriate errors.
|
|
597
|
-
*/
|
|
598
|
-
async handleResponse(response, method, path, durationMs) {
|
|
599
|
-
if (response.status === 401) {
|
|
600
|
-
const authError = new AuthenticationError();
|
|
601
|
-
logApiCall(logger2, method, path, {
|
|
602
|
-
statusCode: response.status,
|
|
603
|
-
durationMs,
|
|
604
|
-
error: authError
|
|
605
|
-
});
|
|
606
|
-
throw authError;
|
|
607
|
-
}
|
|
608
|
-
if (response.status === 429) {
|
|
609
|
-
const retryAfter = response.headers.get("Retry-After");
|
|
610
|
-
const rateError = new RateLimitError(
|
|
611
|
-
"Rate limit exceeded",
|
|
612
|
-
retryAfter ? parseInt(retryAfter, 10) : void 0
|
|
613
|
-
);
|
|
614
|
-
logger2.warning(`Rate limited: ${method} ${path}`, {
|
|
615
|
-
method,
|
|
616
|
-
path,
|
|
617
|
-
statusCode: response.status,
|
|
618
|
-
retryAfter,
|
|
619
|
-
durationMs: Math.round(durationMs * 100) / 100
|
|
620
|
-
});
|
|
621
|
-
throw rateError;
|
|
622
|
-
}
|
|
623
|
-
if (response.status >= 500) {
|
|
624
|
-
const serverError = new ServerError(`Server error: ${response.status}`);
|
|
625
|
-
logApiCall(logger2, method, path, {
|
|
626
|
-
statusCode: response.status,
|
|
627
|
-
durationMs,
|
|
628
|
-
error: serverError
|
|
629
|
-
});
|
|
630
|
-
throw serverError;
|
|
631
|
-
}
|
|
632
|
-
let data;
|
|
633
|
-
try {
|
|
634
|
-
const text = await response.text();
|
|
635
|
-
data = text ? JSON.parse(text) : {};
|
|
636
|
-
} catch {
|
|
637
|
-
if (response.status >= 400) {
|
|
638
|
-
const parseError = new NaturalError(
|
|
639
|
-
`Request failed: ${response.status} (non-JSON response)`,
|
|
640
|
-
{ statusCode: response.status, code: "parse_error" }
|
|
641
|
-
);
|
|
642
|
-
logApiCall(logger2, method, path, {
|
|
643
|
-
statusCode: response.status,
|
|
644
|
-
durationMs,
|
|
645
|
-
error: parseError
|
|
646
|
-
});
|
|
647
|
-
throw parseError;
|
|
648
|
-
}
|
|
649
|
-
logApiCall(logger2, method, path, { statusCode: response.status, durationMs });
|
|
650
|
-
return {};
|
|
651
|
-
}
|
|
652
|
-
if (response.status >= 400) {
|
|
653
|
-
const errBody = data;
|
|
654
|
-
const errors = Array.isArray(errBody.errors) ? errBody.errors : [];
|
|
655
|
-
const firstError = errors[0] ?? {};
|
|
656
|
-
const errorMessage = firstError.detail ?? errBody.detail ?? errBody.message ?? errBody.error ?? "Request failed";
|
|
657
|
-
const errorCode = firstError.code ?? errBody.code ?? "unknown_error";
|
|
658
|
-
const requestError = new InvalidRequestError(
|
|
659
|
-
`${errorMessage} (status=${response.status})`,
|
|
660
|
-
errorCode
|
|
661
|
-
);
|
|
662
|
-
logApiCall(logger2, method, path, {
|
|
663
|
-
statusCode: response.status,
|
|
664
|
-
durationMs,
|
|
665
|
-
error: requestError
|
|
666
|
-
});
|
|
667
|
-
throw requestError;
|
|
668
|
-
}
|
|
669
|
-
logApiCall(logger2, method, path, { statusCode: response.status, durationMs });
|
|
670
|
-
return data;
|
|
671
|
-
}
|
|
672
|
-
/**
|
|
673
|
-
* Register agent config with the observability service.
|
|
674
|
-
*
|
|
675
|
-
* Called lazily before the first request. Errors are caught and logged,
|
|
676
|
-
* never thrown.
|
|
677
|
-
*/
|
|
678
|
-
async registerConfig() {
|
|
679
|
-
if (!this.agentConfig) return;
|
|
680
|
-
try {
|
|
681
|
-
const jwt = await this.getJwt();
|
|
682
|
-
const hash = configHash(this.agentConfig);
|
|
683
|
-
const body = {
|
|
684
|
-
config_hash: hash,
|
|
685
|
-
...agentConfigToDict(this.agentConfig)
|
|
686
|
-
};
|
|
687
|
-
const controller = new AbortController();
|
|
688
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
689
|
-
try {
|
|
690
|
-
const response = await fetch(`${this.baseUrl}/agents/config`, {
|
|
691
|
-
method: "POST",
|
|
692
|
-
headers: {
|
|
693
|
-
Authorization: `Bearer ${jwt}`,
|
|
694
|
-
"Content-Type": "application/json",
|
|
695
|
-
"User-Agent": `naturalpay-ts/${VERSION}`
|
|
696
|
-
},
|
|
697
|
-
body: JSON.stringify(body),
|
|
698
|
-
signal: controller.signal
|
|
699
|
-
});
|
|
700
|
-
if (response.ok) {
|
|
701
|
-
this._configResolved = true;
|
|
702
|
-
} else if (response.status === 429 || response.status === 408 || response.status >= 500) {
|
|
703
|
-
this._nextRetryAt = Date.now() + this._retryBackoffMs;
|
|
704
|
-
this._retryBackoffMs = Math.min(
|
|
705
|
-
this._retryBackoffMs * 2,
|
|
706
|
-
_HTTPClient.MAX_RETRY_BACKOFF_MS
|
|
707
|
-
);
|
|
708
|
-
logger2.warning("Agent config registration failed (transient)", {
|
|
709
|
-
statusCode: response.status
|
|
710
|
-
});
|
|
711
|
-
} else {
|
|
712
|
-
this._configResolved = true;
|
|
713
|
-
logger2.warning("Agent config registration failed (permanent)", {
|
|
714
|
-
statusCode: response.status
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
|
-
} finally {
|
|
718
|
-
clearTimeout(timeoutId);
|
|
719
|
-
}
|
|
720
|
-
} catch (error) {
|
|
721
|
-
this._nextRetryAt = Date.now() + this._retryBackoffMs;
|
|
722
|
-
this._retryBackoffMs = Math.min(this._retryBackoffMs * 2, _HTTPClient.MAX_RETRY_BACKOFF_MS);
|
|
723
|
-
logger2.warning("Failed to register agent config", {
|
|
724
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
725
|
-
});
|
|
726
|
-
} finally {
|
|
727
|
-
this._configAttempted = true;
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
/**
|
|
731
|
-
* Add agent config hash and model usage headers if configured.
|
|
732
|
-
*/
|
|
733
|
-
injectModelContextHeaders(headers, modelUsage) {
|
|
734
|
-
if (this.agentConfig) {
|
|
735
|
-
headers["X-Model-Config-Hash"] = configHash(this.agentConfig);
|
|
736
|
-
}
|
|
737
|
-
const effectiveUsage = (() => {
|
|
738
|
-
if (!modelUsage && !this._defaultModelUsage) return void 0;
|
|
739
|
-
return {
|
|
740
|
-
model: modelUsage?.model ?? this._defaultModelUsage?.model,
|
|
741
|
-
provider: modelUsage?.provider ?? this._defaultModelUsage?.provider,
|
|
742
|
-
inputTokens: modelUsage?.inputTokens,
|
|
743
|
-
outputTokens: modelUsage?.outputTokens,
|
|
744
|
-
toolsCalled: modelUsage?.toolsCalled
|
|
745
|
-
};
|
|
746
|
-
})();
|
|
747
|
-
if (effectiveUsage) {
|
|
748
|
-
const usageDict = modelUsageToDict(effectiveUsage);
|
|
749
|
-
if (Object.keys(usageDict).length > 0) {
|
|
750
|
-
headers["X-Model-Usage"] = Buffer.from(JSON.stringify(usageDict)).toString("base64");
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
/**
|
|
755
|
-
* Make an authenticated request with automatic retries.
|
|
756
|
-
*/
|
|
757
|
-
async request(method, path, options) {
|
|
758
|
-
if (this.agentConfig && !this._configResolved) {
|
|
759
|
-
if (!this._registerConfigPromise) {
|
|
760
|
-
if (!this._configAttempted || Date.now() >= this._nextRetryAt) {
|
|
761
|
-
this._registerConfigPromise = this.registerConfig().catch(() => {
|
|
762
|
-
}).finally(() => {
|
|
763
|
-
this._registerConfigPromise = null;
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
if (!this._configAttempted) {
|
|
768
|
-
await this._registerConfigPromise;
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
const jwt = await this.getJwt();
|
|
772
|
-
const url = this.buildUrl(path, options?.params);
|
|
773
|
-
const mergedHeaders = {
|
|
774
|
-
Authorization: `Bearer ${jwt}`,
|
|
775
|
-
"Content-Type": "application/json",
|
|
776
|
-
"User-Agent": `naturalpay-ts/${VERSION}`
|
|
777
|
-
};
|
|
778
|
-
const toolCallHeader = getToolCallHeader();
|
|
779
|
-
if (toolCallHeader) {
|
|
780
|
-
mergedHeaders["X-Tool-Call"] = toolCallHeader;
|
|
781
|
-
}
|
|
782
|
-
this.injectModelContextHeaders(mergedHeaders, options?.modelUsage);
|
|
783
|
-
if (options?.headers) {
|
|
784
|
-
Object.assign(mergedHeaders, options.headers);
|
|
785
|
-
}
|
|
786
|
-
const bodyStr = options?.body ? JSON.stringify(options.body) : void 0;
|
|
787
|
-
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
788
|
-
const controller = new AbortController();
|
|
789
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
790
|
-
const startTime = Date.now();
|
|
791
|
-
if (attempt === 0) {
|
|
792
|
-
logger2.debug(`API request: ${method} ${path}`, {
|
|
793
|
-
method,
|
|
794
|
-
path,
|
|
795
|
-
hasBody: !!options?.body
|
|
796
|
-
});
|
|
797
|
-
}
|
|
798
|
-
try {
|
|
799
|
-
const response = await fetch(url, {
|
|
800
|
-
method,
|
|
801
|
-
headers: mergedHeaders,
|
|
802
|
-
body: bodyStr,
|
|
803
|
-
signal: controller.signal
|
|
804
|
-
});
|
|
805
|
-
clearTimeout(timeoutId);
|
|
806
|
-
const durationMs = Date.now() - startTime;
|
|
807
|
-
return await this.handleResponse(response, method, path, durationMs);
|
|
808
|
-
} catch (error) {
|
|
809
|
-
clearTimeout(timeoutId);
|
|
810
|
-
const durationMs = Date.now() - startTime;
|
|
811
|
-
let sdkError;
|
|
812
|
-
if (error instanceof NaturalError) {
|
|
813
|
-
sdkError = error;
|
|
814
|
-
} else if (error instanceof Error && error.name === "AbortError") {
|
|
815
|
-
sdkError = new NaturalError("Request timed out");
|
|
816
|
-
logApiCall(logger2, method, path, { durationMs, error: sdkError });
|
|
817
|
-
} else {
|
|
818
|
-
sdkError = new NaturalError(
|
|
819
|
-
`Network error: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
820
|
-
);
|
|
821
|
-
logApiCall(logger2, method, path, { durationMs, error: sdkError });
|
|
822
|
-
}
|
|
823
|
-
if (shouldRetry(method, mergedHeaders, sdkError, attempt, this.maxRetries)) {
|
|
824
|
-
const retryAfter = sdkError instanceof RateLimitError ? sdkError.retryAfter : void 0;
|
|
825
|
-
const delay = calculateRetryDelay(attempt, retryAfter);
|
|
826
|
-
logger2.warning(`Retrying ${method} ${path} (attempt ${attempt + 1}/${this.maxRetries})`, {
|
|
827
|
-
method,
|
|
828
|
-
path,
|
|
829
|
-
attempt: attempt + 1,
|
|
830
|
-
maxRetries: this.maxRetries,
|
|
831
|
-
delayMs: Math.round(delay),
|
|
832
|
-
reason: sdkError instanceof ServerError ? `status ${sdkError.statusCode}` : sdkError instanceof RateLimitError ? "429 rate limited" : "network error"
|
|
833
|
-
});
|
|
834
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
835
|
-
continue;
|
|
836
|
-
}
|
|
837
|
-
throw sdkError;
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
throw new NaturalError("Unexpected retry exhaustion");
|
|
841
|
-
}
|
|
842
|
-
async get(path, options) {
|
|
843
|
-
return this.request("GET", path, options);
|
|
844
|
-
}
|
|
845
|
-
async post(path, options) {
|
|
846
|
-
return this.request("POST", path, options);
|
|
847
|
-
}
|
|
848
|
-
async put(path, options) {
|
|
849
|
-
return this.request("PUT", path, options);
|
|
850
|
-
}
|
|
851
|
-
async delete(path, options) {
|
|
852
|
-
return this.request("DELETE", path, options);
|
|
853
|
-
}
|
|
854
|
-
};
|
|
855
|
-
|
|
856
|
-
// src/resources/base.ts
|
|
857
|
-
var BaseResource = class {
|
|
858
|
-
http;
|
|
859
|
-
constructor(http) {
|
|
860
|
-
this.http = http;
|
|
861
|
-
}
|
|
862
|
-
};
|
|
863
|
-
function sanitizeHeaderValue(value) {
|
|
864
|
-
return value.replace(/[\x00-\x1f\x7f]/g, "");
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
// src/resources/transactions.ts
|
|
868
|
-
function unwrapTransactionResource(resource) {
|
|
869
|
-
if (resource.type !== "transaction" || !resource.attributes) {
|
|
870
|
-
throw new NaturalError(
|
|
871
|
-
`Unexpected resource format: expected type "transaction", got "${resource.type}"`
|
|
872
|
-
);
|
|
873
|
-
}
|
|
874
|
-
const { id, attributes, relationships } = resource;
|
|
875
|
-
return {
|
|
876
|
-
transactionId: id,
|
|
877
|
-
amount: Number(attributes.amount),
|
|
878
|
-
currency: String(attributes.currency),
|
|
879
|
-
status: String(attributes.status),
|
|
880
|
-
description: attributes.description != null ? String(attributes.description) : void 0,
|
|
881
|
-
memo: attributes.memo != null ? String(attributes.memo) : void 0,
|
|
882
|
-
createdAt: String(attributes.createdAt),
|
|
883
|
-
updatedAt: attributes.updatedAt != null ? String(attributes.updatedAt) : void 0,
|
|
884
|
-
isDelegated: Boolean(attributes.isDelegated),
|
|
885
|
-
customerName: attributes.customerName != null ? String(attributes.customerName) : void 0,
|
|
886
|
-
customerAgentId: attributes.customerAgentId != null ? String(attributes.customerAgentId) : void 0,
|
|
887
|
-
senderName: attributes.senderName != null ? String(attributes.senderName) : void 0,
|
|
888
|
-
recipientName: attributes.recipientName != null ? String(attributes.recipientName) : void 0,
|
|
889
|
-
transactionType: String(attributes.transactionType),
|
|
890
|
-
category: String(attributes.category),
|
|
891
|
-
direction: String(attributes.direction),
|
|
892
|
-
sourcePartyId: relationships?.sourceParty?.data?.id,
|
|
893
|
-
destinationPartyId: relationships?.destinationParty?.data?.id,
|
|
894
|
-
sourceWalletId: relationships?.sourceWallet?.data?.id,
|
|
895
|
-
destinationWalletId: relationships?.destinationWallet?.data?.id,
|
|
896
|
-
instanceId: attributes.instanceId != null ? String(attributes.instanceId) : void 0,
|
|
897
|
-
claimLink: attributes.claimLink != null ? String(attributes.claimLink) : void 0
|
|
898
|
-
};
|
|
899
|
-
}
|
|
900
|
-
var TransactionsResource = class extends BaseResource {
|
|
901
|
-
/**
|
|
902
|
-
* Get a transaction by ID.
|
|
903
|
-
*
|
|
904
|
-
* @param transactionId - Transaction ID (txn_xxx)
|
|
905
|
-
* @param params - Optional parameters for observability
|
|
906
|
-
* @returns Transaction details
|
|
907
|
-
*/
|
|
908
|
-
async get(transactionId, params) {
|
|
909
|
-
const headers = {};
|
|
910
|
-
if (params?.agentId) {
|
|
911
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
912
|
-
}
|
|
913
|
-
if (params?.instanceId) {
|
|
914
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
915
|
-
}
|
|
916
|
-
if (params?.traceId) {
|
|
917
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
918
|
-
}
|
|
919
|
-
const queryParams = {};
|
|
920
|
-
if (params?.customerPartyId) {
|
|
921
|
-
queryParams["partyId"] = params.customerPartyId;
|
|
922
|
-
}
|
|
923
|
-
const response = await this.http.get(`/transactions/${transactionId}`, {
|
|
924
|
-
params: Object.keys(queryParams).length > 0 ? queryParams : void 0,
|
|
925
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
926
|
-
});
|
|
927
|
-
if (!response?.data) {
|
|
928
|
-
throw new NaturalError('Unexpected response format: missing "data" in transaction response');
|
|
929
|
-
}
|
|
930
|
-
return unwrapTransactionResource(response.data);
|
|
931
|
-
}
|
|
932
|
-
/**
|
|
933
|
-
* List recent transactions.
|
|
934
|
-
*
|
|
935
|
-
* @param params - List parameters including agent context
|
|
936
|
-
* @returns TransactionListResponse with transactions and pagination info
|
|
937
|
-
*/
|
|
938
|
-
async list(params) {
|
|
939
|
-
const headers = {};
|
|
940
|
-
if (params?.agentId) {
|
|
941
|
-
if (!params?.instanceId) {
|
|
942
|
-
throw new InvalidRequestError("instanceId is required when agentId is provided");
|
|
943
|
-
}
|
|
944
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
945
|
-
}
|
|
946
|
-
if (params?.instanceId) {
|
|
947
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
948
|
-
}
|
|
949
|
-
if (params?.traceId) {
|
|
950
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
951
|
-
}
|
|
952
|
-
const queryParams = {
|
|
953
|
-
limit: params?.limit ?? 50,
|
|
954
|
-
cursor: params?.cursor,
|
|
955
|
-
type: params?.type
|
|
956
|
-
};
|
|
957
|
-
const response = await this.http.get("/transactions", {
|
|
958
|
-
params: queryParams,
|
|
959
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
960
|
-
});
|
|
961
|
-
if (!response?.data || !Array.isArray(response.data)) {
|
|
962
|
-
throw new NaturalError(
|
|
963
|
-
'Unexpected response format: missing "data" array in transaction list response'
|
|
964
|
-
);
|
|
965
|
-
}
|
|
966
|
-
const transactions = response.data.map(unwrapTransactionResource);
|
|
967
|
-
const pagination = response.meta?.pagination ?? {};
|
|
968
|
-
return {
|
|
969
|
-
transactions,
|
|
970
|
-
hasMore: pagination.hasMore ?? false,
|
|
971
|
-
nextCursor: pagination.nextCursor ?? null
|
|
972
|
-
};
|
|
973
|
-
}
|
|
974
|
-
};
|
|
975
|
-
|
|
976
|
-
// src/resources/payments.ts
|
|
977
|
-
var PHONE_DIGITS_RE = /^\d{10,}$/;
|
|
978
|
-
var PHONE_PLUS_RE = /^\+\d{7,}$/;
|
|
979
|
-
function validateRecipient(recipient) {
|
|
980
|
-
if (!recipient) {
|
|
981
|
-
throw new InvalidRequestError("recipient cannot be empty");
|
|
982
|
-
}
|
|
983
|
-
if (recipient.startsWith("pty_")) return;
|
|
984
|
-
if (recipient.includes("@")) return;
|
|
985
|
-
if (PHONE_PLUS_RE.test(recipient)) return;
|
|
986
|
-
if (PHONE_DIGITS_RE.test(recipient)) return;
|
|
987
|
-
throw new InvalidRequestError(
|
|
988
|
-
"Invalid recipient format. Expected: party ID (pty_*), email (contains @), or phone (+ prefix or 10+ digits)"
|
|
989
|
-
);
|
|
990
|
-
}
|
|
991
|
-
function unwrapPaymentResponse(response) {
|
|
992
|
-
if (!response?.data) {
|
|
993
|
-
throw new NaturalError('Unexpected response format: missing "data" field in payment response');
|
|
994
|
-
}
|
|
995
|
-
const base = unwrapTransactionResource(response.data);
|
|
996
|
-
const { relationships, attributes } = response.data;
|
|
997
|
-
return {
|
|
998
|
-
...base,
|
|
999
|
-
// Payment responses may omit these fields; provide sensible defaults.
|
|
1000
|
-
transactionType: String(attributes.transactionType ?? "payment"),
|
|
1001
|
-
category: String(attributes.category ?? "sent"),
|
|
1002
|
-
direction: String(attributes.direction ?? "OUTBOUND"),
|
|
1003
|
-
// Mirror description into memo for payment convenience.
|
|
1004
|
-
memo: base.description,
|
|
1005
|
-
// Payments use customerParty/counterparty relationship keys,
|
|
1006
|
-
// falling back to the generic sourceParty/destinationParty.
|
|
1007
|
-
sourcePartyId: relationships?.customerParty?.data?.id ?? base.sourcePartyId,
|
|
1008
|
-
destinationPartyId: relationships?.counterparty?.data?.id ?? base.destinationPartyId
|
|
1009
|
-
};
|
|
1010
|
-
}
|
|
1011
|
-
var PaymentsResource = class extends BaseResource {
|
|
1012
|
-
/**
|
|
1013
|
-
* Create a payment.
|
|
1014
|
-
*
|
|
1015
|
-
* @param params - Payment creation parameters
|
|
1016
|
-
* @returns Transaction object with transaction_id (txn_*), status, etc.
|
|
1017
|
-
*/
|
|
1018
|
-
async create(params) {
|
|
1019
|
-
const recipient = params.recipient.trim();
|
|
1020
|
-
validateRecipient(recipient);
|
|
1021
|
-
if (!Number.isInteger(params.amount) || params.amount <= 0) {
|
|
1022
|
-
throw new InvalidRequestError("amount must be a positive integer (minor units in cents)");
|
|
1023
|
-
}
|
|
1024
|
-
const attributes = {
|
|
1025
|
-
amount: params.amount,
|
|
1026
|
-
currency: params.currency ?? "USD",
|
|
1027
|
-
counterparty: recipient,
|
|
1028
|
-
customerPartyId: params.customerPartyId
|
|
1029
|
-
};
|
|
1030
|
-
attributes["description"] = params.memo;
|
|
1031
|
-
const body = { data: { attributes } };
|
|
1032
|
-
const headers = {
|
|
1033
|
-
"Idempotency-Key": params.idempotencyKey
|
|
1034
|
-
};
|
|
1035
|
-
if (params.agentId) {
|
|
1036
|
-
if (!params.instanceId) {
|
|
1037
|
-
throw new InvalidRequestError("instanceId is required when agentId is provided");
|
|
1038
|
-
}
|
|
1039
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1040
|
-
}
|
|
1041
|
-
if (params.instanceId) {
|
|
1042
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1043
|
-
}
|
|
1044
|
-
if (params.traceId) {
|
|
1045
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1046
|
-
}
|
|
1047
|
-
const response = await this.http.post("/payments", {
|
|
1048
|
-
body,
|
|
1049
|
-
headers
|
|
1050
|
-
});
|
|
1051
|
-
return unwrapPaymentResponse(response);
|
|
1052
|
-
}
|
|
1053
|
-
};
|
|
1054
|
-
|
|
1055
|
-
// src/resources/wallet.ts
|
|
1056
|
-
function toAmountInfo(raw) {
|
|
1057
|
-
const obj = raw;
|
|
1058
|
-
return {
|
|
1059
|
-
amountMinor: Number(obj?.amountMinor ?? 0)
|
|
1060
|
-
};
|
|
1061
|
-
}
|
|
1062
|
-
function unwrapBalance(response) {
|
|
1063
|
-
if (!response?.data) {
|
|
1064
|
-
throw new NaturalError(
|
|
1065
|
-
'Unexpected response format: missing "data" field in wallet balance response'
|
|
1066
|
-
);
|
|
1067
|
-
}
|
|
1068
|
-
const { data } = response;
|
|
1069
|
-
if (data.type !== "walletBalance" || !data.attributes) {
|
|
1070
|
-
throw new NaturalError(
|
|
1071
|
-
`Unexpected resource format: expected type "walletBalance", got "${data.type}"`
|
|
1072
|
-
);
|
|
1073
|
-
}
|
|
1074
|
-
const { id, attributes } = data;
|
|
1075
|
-
const rawBreakdown = attributes.breakdown;
|
|
1076
|
-
const breakdown = {
|
|
1077
|
-
operatingFunded: toAmountInfo(rawBreakdown?.operatingFunded),
|
|
1078
|
-
operatingAdvanced: toAmountInfo(rawBreakdown?.operatingAdvanced),
|
|
1079
|
-
escrowFundedSettled: toAmountInfo(rawBreakdown?.escrowFundedSettled),
|
|
1080
|
-
escrowAdvanced: toAmountInfo(rawBreakdown?.escrowAdvanced),
|
|
1081
|
-
holdsOutbound: toAmountInfo(rawBreakdown?.holdsOutbound)
|
|
1082
|
-
};
|
|
1083
|
-
return {
|
|
1084
|
-
walletId: id,
|
|
1085
|
-
breakdown,
|
|
1086
|
-
available: toAmountInfo(attributes.available),
|
|
1087
|
-
pendingClaimAmountMinor: attributes.pendingClaimAmountMinor != null ? Number(attributes.pendingClaimAmountMinor) : void 0,
|
|
1088
|
-
pendingClaimCount: attributes.pendingClaimCount != null ? Number(attributes.pendingClaimCount) : void 0
|
|
1089
|
-
};
|
|
1090
|
-
}
|
|
1091
|
-
function unwrapWithdrawal(response) {
|
|
1092
|
-
if (!response?.data) {
|
|
1093
|
-
throw new NaturalError(
|
|
1094
|
-
'Unexpected response format: missing "data" field in withdrawal response'
|
|
1095
|
-
);
|
|
1096
|
-
}
|
|
1097
|
-
const { data } = response;
|
|
1098
|
-
if (data.type !== "withdrawal" || !data.attributes) {
|
|
1099
|
-
throw new NaturalError(
|
|
1100
|
-
`Unexpected resource format: expected type "withdrawal", got "${data.type}"`
|
|
1101
|
-
);
|
|
1102
|
-
}
|
|
1103
|
-
const { id, attributes } = data;
|
|
1104
|
-
return {
|
|
1105
|
-
transferId: id ?? void 0,
|
|
1106
|
-
instructionId: attributes.instructionId != null ? String(attributes.instructionId) : void 0,
|
|
1107
|
-
status: String(attributes.status),
|
|
1108
|
-
amount: attributes.amount != null ? Number(attributes.amount) : 0,
|
|
1109
|
-
currency: String(attributes.currency),
|
|
1110
|
-
estimatedSettlement: attributes.estimatedSettlement != null ? String(attributes.estimatedSettlement) : void 0,
|
|
1111
|
-
kycRequired: Boolean(attributes.kycRequired),
|
|
1112
|
-
kycStatus: attributes.kycStatus != null ? String(attributes.kycStatus) : void 0,
|
|
1113
|
-
kycSessionUrl: attributes.kycSessionUrl != null ? String(attributes.kycSessionUrl) : void 0,
|
|
1114
|
-
mfaRequired: Boolean(attributes.mfaRequired),
|
|
1115
|
-
mfaChallengeId: attributes.mfaChallengeId != null ? String(attributes.mfaChallengeId) : void 0,
|
|
1116
|
-
mfaExpiresAt: attributes.mfaExpiresAt != null ? String(attributes.mfaExpiresAt) : void 0,
|
|
1117
|
-
error: attributes.error != null ? String(attributes.error) : void 0,
|
|
1118
|
-
errorDetails: attributes.errorDetails != null ? String(attributes.errorDetails) : void 0
|
|
1119
|
-
};
|
|
1120
|
-
}
|
|
1121
|
-
var WalletResource = class extends BaseResource {
|
|
1122
|
-
/**
|
|
1123
|
-
* Get current wallet balance.
|
|
1124
|
-
*
|
|
1125
|
-
* @returns AccountBalance with available, current, pending amounts
|
|
1126
|
-
*/
|
|
1127
|
-
async balance(options) {
|
|
1128
|
-
const headers = {};
|
|
1129
|
-
if (options?.agentId) {
|
|
1130
|
-
headers["X-Agent-ID"] = options.agentId;
|
|
1131
|
-
}
|
|
1132
|
-
if (options?.instanceId) {
|
|
1133
|
-
headers["X-Instance-ID"] = options.instanceId;
|
|
1134
|
-
}
|
|
1135
|
-
if (options?.traceId) {
|
|
1136
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(options.traceId);
|
|
1137
|
-
}
|
|
1138
|
-
const params = {};
|
|
1139
|
-
if (options?.customerPartyId) {
|
|
1140
|
-
params["partyId"] = options.customerPartyId;
|
|
1141
|
-
}
|
|
1142
|
-
const response = await this.http.get("/wallet/balance", {
|
|
1143
|
-
params: Object.keys(params).length > 0 ? params : void 0,
|
|
1144
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1145
|
-
});
|
|
1146
|
-
return unwrapBalance(response);
|
|
1147
|
-
}
|
|
1148
|
-
/**
|
|
1149
|
-
* Initiate a withdrawal to a linked bank account.
|
|
1150
|
-
*
|
|
1151
|
-
* @param params - Withdrawal parameters
|
|
1152
|
-
* @returns WithdrawResponse with transfer status (may require KYC/MFA)
|
|
1153
|
-
*/
|
|
1154
|
-
async withdraw(params) {
|
|
1155
|
-
if (!Number.isInteger(params.amount) || params.amount <= 0) {
|
|
1156
|
-
throw new InvalidRequestError("amount must be a positive integer (minor units in cents)");
|
|
1157
|
-
}
|
|
1158
|
-
const attributes = {
|
|
1159
|
-
amount: params.amount,
|
|
1160
|
-
currency: params.currency ?? "USD",
|
|
1161
|
-
externalFundingSourceId: params.externalFundingSourceId
|
|
1162
|
-
};
|
|
1163
|
-
if (params.description) attributes["description"] = params.description;
|
|
1164
|
-
const body = { data: { attributes } };
|
|
1165
|
-
const headers = {
|
|
1166
|
-
"Idempotency-Key": params.idempotencyKey
|
|
1167
|
-
};
|
|
1168
|
-
if (params.agentId) {
|
|
1169
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1170
|
-
}
|
|
1171
|
-
if (params.instanceId) {
|
|
1172
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1173
|
-
}
|
|
1174
|
-
if (params.traceId) {
|
|
1175
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1176
|
-
}
|
|
1177
|
-
const response = await this.http.post("/wallet/withdraw", {
|
|
1178
|
-
body,
|
|
1179
|
-
headers
|
|
1180
|
-
});
|
|
1181
|
-
return unwrapWithdrawal(response);
|
|
1182
|
-
}
|
|
1183
|
-
};
|
|
1184
|
-
|
|
1185
|
-
// src/resources/agents.ts
|
|
1186
|
-
function unwrapAgentResource(resource) {
|
|
1187
|
-
if (resource.type !== "agent" || !resource.attributes) {
|
|
1188
|
-
throw new NaturalError(
|
|
1189
|
-
`Unexpected resource format: expected type "agent", got "${resource.type}"`
|
|
1190
|
-
);
|
|
1191
|
-
}
|
|
1192
|
-
const { id, attributes, relationships } = resource;
|
|
1193
|
-
return {
|
|
1194
|
-
id,
|
|
1195
|
-
name: String(attributes.name),
|
|
1196
|
-
description: attributes.description != null ? String(attributes.description) : void 0,
|
|
1197
|
-
status: String(attributes.status),
|
|
1198
|
-
partyId: relationships?.party?.data?.id ?? "",
|
|
1199
|
-
createdAt: attributes.createdAt != null ? String(attributes.createdAt) : void 0,
|
|
1200
|
-
createdBy: attributes.createdBy != null ? String(attributes.createdBy) : void 0,
|
|
1201
|
-
updatedAt: attributes.updatedAt != null ? String(attributes.updatedAt) : void 0,
|
|
1202
|
-
updatedBy: attributes.updatedBy != null ? String(attributes.updatedBy) : void 0
|
|
1203
|
-
};
|
|
1204
|
-
}
|
|
1205
|
-
function unwrapAgent(response) {
|
|
1206
|
-
if (!response?.data) {
|
|
1207
|
-
throw new NaturalError('Unexpected response format: missing "data" field in agent response');
|
|
1208
|
-
}
|
|
1209
|
-
return unwrapAgentResource(response.data);
|
|
1210
|
-
}
|
|
1211
|
-
function unwrapAgentList(response) {
|
|
1212
|
-
if (!response?.data || !Array.isArray(response.data)) {
|
|
1213
|
-
throw new NaturalError(
|
|
1214
|
-
'Unexpected response format: missing "data" array in agent list response'
|
|
1215
|
-
);
|
|
1216
|
-
}
|
|
1217
|
-
const agents = response.data.map(unwrapAgentResource);
|
|
1218
|
-
const pagination = response.meta?.pagination ?? {};
|
|
1219
|
-
return {
|
|
1220
|
-
agents,
|
|
1221
|
-
hasMore: pagination.hasMore ?? false,
|
|
1222
|
-
nextCursor: pagination.nextCursor ?? null
|
|
1223
|
-
};
|
|
1224
|
-
}
|
|
1225
|
-
var AgentsResource = class extends BaseResource {
|
|
1226
|
-
/**
|
|
1227
|
-
* List agents for the partner.
|
|
1228
|
-
*
|
|
1229
|
-
* @param params - Filter and pagination parameters
|
|
1230
|
-
* @returns AgentListResponse with list of agents
|
|
1231
|
-
*/
|
|
1232
|
-
async list(params) {
|
|
1233
|
-
const headers = {};
|
|
1234
|
-
if (params?.agentId) {
|
|
1235
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1236
|
-
}
|
|
1237
|
-
if (params?.instanceId) {
|
|
1238
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1239
|
-
}
|
|
1240
|
-
if (params?.traceId) {
|
|
1241
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1242
|
-
}
|
|
1243
|
-
const queryParams = {
|
|
1244
|
-
status: params?.status,
|
|
1245
|
-
limit: params?.limit ?? 50,
|
|
1246
|
-
cursor: params?.cursor
|
|
1247
|
-
};
|
|
1248
|
-
const response = await this.http.get("/agents", {
|
|
1249
|
-
params: queryParams,
|
|
1250
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1251
|
-
});
|
|
1252
|
-
return unwrapAgentList(response);
|
|
1253
|
-
}
|
|
1254
|
-
/**
|
|
1255
|
-
* Get agent by ID.
|
|
1256
|
-
*
|
|
1257
|
-
* @param agentId - The agent ID to retrieve (agt_xxx)
|
|
1258
|
-
* @returns Agent details
|
|
1259
|
-
*/
|
|
1260
|
-
async get(agentId, options) {
|
|
1261
|
-
const headers = {};
|
|
1262
|
-
if (options?.agentId) {
|
|
1263
|
-
headers["X-Agent-ID"] = options.agentId;
|
|
1264
|
-
}
|
|
1265
|
-
if (options?.instanceId) {
|
|
1266
|
-
headers["X-Instance-ID"] = options.instanceId;
|
|
1267
|
-
}
|
|
1268
|
-
if (options?.traceId) {
|
|
1269
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(options.traceId);
|
|
1270
|
-
}
|
|
1271
|
-
const response = await this.http.get(`/agents/${agentId}`, {
|
|
1272
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1273
|
-
});
|
|
1274
|
-
return unwrapAgent(response);
|
|
1275
|
-
}
|
|
1276
|
-
/**
|
|
1277
|
-
* Create a new agent.
|
|
1278
|
-
*
|
|
1279
|
-
* @param params - Agent creation parameters
|
|
1280
|
-
* @returns AgentCreateResponse with created agent details
|
|
1281
|
-
*/
|
|
1282
|
-
async create(params) {
|
|
1283
|
-
const attributes = {
|
|
1284
|
-
name: params.name
|
|
1285
|
-
};
|
|
1286
|
-
if (params.description) {
|
|
1287
|
-
attributes["description"] = params.description;
|
|
1288
|
-
}
|
|
1289
|
-
if (params.limits) {
|
|
1290
|
-
attributes["limits"] = params.limits;
|
|
1291
|
-
}
|
|
1292
|
-
const body = { data: { attributes } };
|
|
1293
|
-
const headers = {};
|
|
1294
|
-
if (params.idempotencyKey) {
|
|
1295
|
-
headers["Idempotency-Key"] = params.idempotencyKey;
|
|
1296
|
-
}
|
|
1297
|
-
if (params.agentId) {
|
|
1298
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1299
|
-
}
|
|
1300
|
-
if (params.instanceId) {
|
|
1301
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1302
|
-
}
|
|
1303
|
-
if (params.traceId) {
|
|
1304
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1305
|
-
}
|
|
1306
|
-
const response = await this.http.post("/agents", {
|
|
1307
|
-
body,
|
|
1308
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1309
|
-
});
|
|
1310
|
-
return unwrapAgent(response);
|
|
1311
|
-
}
|
|
1312
|
-
/**
|
|
1313
|
-
* Update an existing agent.
|
|
1314
|
-
*
|
|
1315
|
-
* @param agentId - The agent ID to update (agt_xxx)
|
|
1316
|
-
* @param params - Update parameters
|
|
1317
|
-
* @returns AgentUpdateResponse with updated agent details
|
|
1318
|
-
*/
|
|
1319
|
-
async update(agentId, params) {
|
|
1320
|
-
const attributes = {};
|
|
1321
|
-
if (params.name !== void 0) attributes["name"] = params.name;
|
|
1322
|
-
if (params.description !== void 0) attributes["description"] = params.description;
|
|
1323
|
-
if (params.status !== void 0) attributes["status"] = params.status;
|
|
1324
|
-
const body = { data: { attributes } };
|
|
1325
|
-
const headers = {};
|
|
1326
|
-
if (params.idempotencyKey) {
|
|
1327
|
-
headers["Idempotency-Key"] = params.idempotencyKey;
|
|
1328
|
-
}
|
|
1329
|
-
if (params.agentId) {
|
|
1330
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1331
|
-
}
|
|
1332
|
-
if (params.instanceId) {
|
|
1333
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1334
|
-
}
|
|
1335
|
-
if (params.traceId) {
|
|
1336
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1337
|
-
}
|
|
1338
|
-
const response = await this.http.put(`/agents/${agentId}`, {
|
|
1339
|
-
body,
|
|
1340
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1341
|
-
});
|
|
1342
|
-
return unwrapAgent(response);
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Delete an agent.
|
|
1346
|
-
*
|
|
1347
|
-
* @param agentId - The agent ID to delete (agt_xxx)
|
|
1348
|
-
* @param options - Optional observability parameters
|
|
1349
|
-
*/
|
|
1350
|
-
async delete(agentId, options) {
|
|
1351
|
-
const headers = {};
|
|
1352
|
-
if (options?.agentId) {
|
|
1353
|
-
headers["X-Agent-ID"] = options.agentId;
|
|
1354
|
-
}
|
|
1355
|
-
if (options?.instanceId) {
|
|
1356
|
-
headers["X-Instance-ID"] = options.instanceId;
|
|
1357
|
-
}
|
|
1358
|
-
if (options?.traceId) {
|
|
1359
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(options.traceId);
|
|
1360
|
-
}
|
|
1361
|
-
await this.http.delete(`/agents/${agentId}`, {
|
|
1362
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1363
|
-
});
|
|
1364
|
-
}
|
|
1365
|
-
};
|
|
1366
|
-
|
|
1367
|
-
// src/resources/delegations.ts
|
|
1368
|
-
function unwrapAgentDelegationResource(resource) {
|
|
1369
|
-
if (resource.type !== "agentDelegation" || !resource.attributes) {
|
|
1370
|
-
throw new NaturalError(
|
|
1371
|
-
`Unexpected resource format: expected type "agentDelegation", got "${resource.type}"`
|
|
1372
|
-
);
|
|
1373
|
-
}
|
|
1374
|
-
const { id, attributes, relationships } = resource;
|
|
1375
|
-
return {
|
|
1376
|
-
id,
|
|
1377
|
-
agentName: attributes.agentName != null ? String(attributes.agentName) : void 0,
|
|
1378
|
-
agentId: relationships?.agent?.data?.id ?? "",
|
|
1379
|
-
delegationId: relationships?.delegation?.data?.id ?? "",
|
|
1380
|
-
delegatorPartyId: relationships?.delegatorParty?.data?.id,
|
|
1381
|
-
delegateePartyId: relationships?.delegateeParty?.data?.id,
|
|
1382
|
-
delegatorPartyName: attributes.delegatorPartyName != null ? String(attributes.delegatorPartyName) : void 0,
|
|
1383
|
-
delegateePartyName: attributes.delegateePartyName != null ? String(attributes.delegateePartyName) : void 0,
|
|
1384
|
-
permissions: Array.isArray(attributes.permissions) ? attributes.permissions : [],
|
|
1385
|
-
limits: attributes.limits != null ? attributes.limits : void 0,
|
|
1386
|
-
expiresAt: attributes.expiresAt != null ? String(attributes.expiresAt) : void 0,
|
|
1387
|
-
createdAt: String(attributes.createdAt),
|
|
1388
|
-
createdBy: attributes.createdBy != null ? String(attributes.createdBy) : void 0,
|
|
1389
|
-
updatedAt: String(attributes.updatedAt)
|
|
1390
|
-
};
|
|
1391
|
-
}
|
|
1392
|
-
function unwrapAgentDelegation(response) {
|
|
1393
|
-
if (!response?.data) {
|
|
1394
|
-
throw new NaturalError(
|
|
1395
|
-
'Unexpected response format: missing "data" field in agent delegation response'
|
|
1396
|
-
);
|
|
1397
|
-
}
|
|
1398
|
-
return unwrapAgentDelegationResource(response.data);
|
|
1399
|
-
}
|
|
1400
|
-
function unwrapAgentDelegationList(response) {
|
|
1401
|
-
if (!response?.data || !Array.isArray(response.data)) {
|
|
1402
|
-
throw new NaturalError(
|
|
1403
|
-
'Unexpected response format: missing "data" array in agent delegation list response'
|
|
1404
|
-
);
|
|
1405
|
-
}
|
|
1406
|
-
const agentDelegations = response.data.map(unwrapAgentDelegationResource);
|
|
1407
|
-
const pagination = response.meta?.pagination ?? {};
|
|
1408
|
-
return {
|
|
1409
|
-
agentDelegations,
|
|
1410
|
-
hasMore: pagination.hasMore ?? false,
|
|
1411
|
-
nextCursor: pagination.nextCursor ?? null
|
|
1412
|
-
};
|
|
1413
|
-
}
|
|
1414
|
-
var DelegationsResource = class extends BaseResource {
|
|
1415
|
-
/**
|
|
1416
|
-
* List agent delegations with optional filters.
|
|
1417
|
-
*
|
|
1418
|
-
* @param params - Filter parameters
|
|
1419
|
-
* @returns AgentDelegationListResponse with list of agent delegations
|
|
1420
|
-
*/
|
|
1421
|
-
async list(params) {
|
|
1422
|
-
const headers = {};
|
|
1423
|
-
if (params?.instanceId) {
|
|
1424
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1425
|
-
}
|
|
1426
|
-
if (params?.traceId) {
|
|
1427
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1428
|
-
}
|
|
1429
|
-
const queryParams = {
|
|
1430
|
-
delegationId: params?.delegationId,
|
|
1431
|
-
agentId: params?.agentId,
|
|
1432
|
-
delegatorPartyId: params?.delegatorPartyId,
|
|
1433
|
-
delegateePartyId: params?.delegateePartyId,
|
|
1434
|
-
includeRevoked: params?.includeRevoked,
|
|
1435
|
-
limit: params?.limit ?? 50,
|
|
1436
|
-
cursor: params?.cursor
|
|
1437
|
-
};
|
|
1438
|
-
const response = await this.http.get("/agent-delegations", {
|
|
1439
|
-
params: queryParams,
|
|
1440
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1441
|
-
});
|
|
1442
|
-
return unwrapAgentDelegationList(response);
|
|
1443
|
-
}
|
|
1444
|
-
/**
|
|
1445
|
-
* Get agent delegation by ID.
|
|
1446
|
-
*
|
|
1447
|
-
* @param agentDelegationId - The agent delegation handle (adl_xxx)
|
|
1448
|
-
* @returns AgentDelegation details
|
|
1449
|
-
*/
|
|
1450
|
-
async get(agentDelegationId) {
|
|
1451
|
-
const response = await this.http.get(
|
|
1452
|
-
`/agent-delegations/${agentDelegationId}`
|
|
1453
|
-
);
|
|
1454
|
-
return unwrapAgentDelegation(response);
|
|
1455
|
-
}
|
|
1456
|
-
};
|
|
1457
|
-
|
|
1458
|
-
// src/resources/customers.ts
|
|
1459
|
-
var VALID_CUSTOMER_TYPES = /* @__PURE__ */ new Set(["party", "delegationInvitation"]);
|
|
1460
|
-
var VALID_WALLET_ACCESS = /* @__PURE__ */ new Set(["granted", "denied", "noWallet"]);
|
|
1461
|
-
function isCustomerType(value) {
|
|
1462
|
-
return VALID_CUSTOMER_TYPES.has(value);
|
|
1463
|
-
}
|
|
1464
|
-
function isWalletAccess(value) {
|
|
1465
|
-
return typeof value === "string" && VALID_WALLET_ACCESS.has(value);
|
|
1466
|
-
}
|
|
1467
|
-
function unwrapCustomerResource(resource) {
|
|
1468
|
-
if (!isCustomerType(resource.type) || !resource.attributes) {
|
|
1469
|
-
throw new NaturalError(
|
|
1470
|
-
`Unexpected resource format: expected type "party" or "delegationInvitation", got "${resource.type}"`
|
|
1471
|
-
);
|
|
1472
|
-
}
|
|
1473
|
-
const { id, attributes } = resource;
|
|
1474
|
-
const party = typeof attributes.party === "object" && attributes.party != null ? {
|
|
1475
|
-
id: String(attributes.party.id),
|
|
1476
|
-
name: String(attributes.party.name),
|
|
1477
|
-
email: typeof attributes.party.email === "string" ? String(attributes.party.email) : void 0
|
|
1478
|
-
} : void 0;
|
|
1479
|
-
return {
|
|
1480
|
-
id,
|
|
1481
|
-
type: resource.type,
|
|
1482
|
-
party,
|
|
1483
|
-
email: typeof attributes.email === "string" ? attributes.email : void 0,
|
|
1484
|
-
status: typeof attributes.status === "string" ? attributes.status : "",
|
|
1485
|
-
permissions: Array.isArray(attributes.permissions) ? attributes.permissions : [],
|
|
1486
|
-
createdAt: typeof attributes.createdAt === "string" ? attributes.createdAt : "",
|
|
1487
|
-
walletAvailableMinor: typeof attributes.walletAvailableMinor === "number" ? attributes.walletAvailableMinor : void 0,
|
|
1488
|
-
walletAvailableDollars: typeof attributes.walletAvailableDollars === "string" ? attributes.walletAvailableDollars : void 0,
|
|
1489
|
-
walletAccess: isWalletAccess(attributes.walletAccess) ? attributes.walletAccess : "denied"
|
|
1490
|
-
};
|
|
1491
|
-
}
|
|
1492
|
-
function unwrapCustomerList(response) {
|
|
1493
|
-
if (!response?.data || !Array.isArray(response.data)) {
|
|
1494
|
-
throw new NaturalError(
|
|
1495
|
-
'Unexpected response format: missing "data" array in customer list response'
|
|
1496
|
-
);
|
|
1497
|
-
}
|
|
1498
|
-
const pagination = response.meta?.pagination ?? {};
|
|
1499
|
-
return {
|
|
1500
|
-
items: response.data.map(unwrapCustomerResource),
|
|
1501
|
-
hasMore: pagination.hasMore ?? false,
|
|
1502
|
-
nextCursor: pagination.nextCursor ?? null
|
|
1503
|
-
};
|
|
1504
|
-
}
|
|
1505
|
-
var CustomersResource = class extends BaseResource {
|
|
1506
|
-
/**
|
|
1507
|
-
* List customers who have delegated access to the partner.
|
|
1508
|
-
*
|
|
1509
|
-
* @param params - Pagination parameters
|
|
1510
|
-
* @returns CustomerListResponse with items, hasMore, nextCursor
|
|
1511
|
-
*/
|
|
1512
|
-
async list(params) {
|
|
1513
|
-
const headers = {};
|
|
1514
|
-
if (params?.agentId) {
|
|
1515
|
-
headers["X-Agent-ID"] = params.agentId;
|
|
1516
|
-
}
|
|
1517
|
-
if (params?.instanceId) {
|
|
1518
|
-
headers["X-Instance-ID"] = params.instanceId;
|
|
1519
|
-
}
|
|
1520
|
-
if (params?.traceId) {
|
|
1521
|
-
headers["X-Trace-ID"] = sanitizeHeaderValue(params.traceId);
|
|
1522
|
-
}
|
|
1523
|
-
const queryParams = {
|
|
1524
|
-
limit: params?.limit,
|
|
1525
|
-
cursor: params?.cursor
|
|
1526
|
-
};
|
|
1527
|
-
const response = await this.http.get("/customers", {
|
|
1528
|
-
params: queryParams,
|
|
1529
|
-
headers: Object.keys(headers).length > 0 ? headers : void 0
|
|
1530
|
-
});
|
|
1531
|
-
return unwrapCustomerList(response);
|
|
1532
|
-
}
|
|
1533
|
-
};
|
|
1534
|
-
|
|
1535
|
-
// src/client.ts
|
|
1536
|
-
var NaturalClient = class {
|
|
1537
|
-
http;
|
|
1538
|
-
/** Payments API resource. */
|
|
1539
|
-
payments;
|
|
1540
|
-
/** Wallet API resource for balance and withdrawals. */
|
|
1541
|
-
wallet;
|
|
1542
|
-
/** Transactions API resource. */
|
|
1543
|
-
transactions;
|
|
1544
|
-
/** Agents API resource for managing agents. */
|
|
1545
|
-
agents;
|
|
1546
|
-
/** Agent delegations API resource. */
|
|
1547
|
-
delegations;
|
|
1548
|
-
/** Customers API resource for listing parties who delegated access. */
|
|
1549
|
-
customers;
|
|
1550
|
-
/**
|
|
1551
|
-
* Initialize the Natural client.
|
|
1552
|
-
*
|
|
1553
|
-
* @param options - Client configuration options
|
|
1554
|
-
* @param options.apiKey - API key (defaults to NATURAL_API_KEY env var)
|
|
1555
|
-
* @param options.baseUrl - API base URL (defaults to https://api.natural.co)
|
|
1556
|
-
* @param options.timeout - Request timeout in milliseconds (default: 30000)
|
|
1557
|
-
*/
|
|
1558
|
-
constructor(options = {}) {
|
|
1559
|
-
this.http = new HTTPClient(options);
|
|
1560
|
-
this.payments = new PaymentsResource(this.http);
|
|
1561
|
-
this.wallet = new WalletResource(this.http);
|
|
1562
|
-
this.transactions = new TransactionsResource(this.http);
|
|
1563
|
-
this.agents = new AgentsResource(this.http);
|
|
1564
|
-
this.delegations = new DelegationsResource(this.http);
|
|
1565
|
-
this.customers = new CustomersResource(this.http);
|
|
1566
|
-
}
|
|
1567
|
-
};
|
|
1568
|
-
var WHSEC_PREFIX = "whsec_";
|
|
1569
|
-
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
1570
|
-
function getHeader(headers, name) {
|
|
1571
|
-
if (typeof headers.get === "function") {
|
|
1572
|
-
return headers.get(name) ?? void 0;
|
|
1573
|
-
}
|
|
1574
|
-
const lower = name.toLowerCase();
|
|
1575
|
-
for (const key of Object.keys(headers)) {
|
|
1576
|
-
if (key.toLowerCase() === lower) {
|
|
1577
|
-
return headers[key];
|
|
1578
|
-
}
|
|
1579
|
-
}
|
|
1580
|
-
return void 0;
|
|
1581
|
-
}
|
|
1582
|
-
function verifyWebhookSignature(body, headers, secret, options) {
|
|
1583
|
-
const tolerance = options?.toleranceInSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
1584
|
-
if (!Number.isInteger(tolerance) || tolerance <= 0) {
|
|
1585
|
-
throw new WebhookVerificationError("toleranceInSeconds must be a positive integer");
|
|
1586
|
-
}
|
|
1587
|
-
const webhookId = getHeader(headers, "webhook-id");
|
|
1588
|
-
if (!webhookId) {
|
|
1589
|
-
throw new WebhookVerificationError("webhook-id header is missing");
|
|
1590
|
-
}
|
|
1591
|
-
const timestampStr = getHeader(headers, "webhook-timestamp");
|
|
1592
|
-
if (!timestampStr) {
|
|
1593
|
-
throw new WebhookVerificationError("webhook-timestamp header is missing");
|
|
1594
|
-
}
|
|
1595
|
-
const signatureHeader = getHeader(headers, "webhook-signature");
|
|
1596
|
-
if (!signatureHeader) {
|
|
1597
|
-
throw new WebhookVerificationError("webhook-signature header is missing");
|
|
1598
|
-
}
|
|
1599
|
-
if (!/^\d+$/.test(timestampStr)) {
|
|
1600
|
-
throw new WebhookVerificationError(
|
|
1601
|
-
`Invalid webhook-timestamp: '${timestampStr}' is not a valid integer`
|
|
1602
|
-
);
|
|
1603
|
-
}
|
|
1604
|
-
const timestamp = parseInt(timestampStr, 10);
|
|
1605
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
1606
|
-
if (Math.abs(now - timestamp) > tolerance) {
|
|
1607
|
-
throw new WebhookVerificationError(
|
|
1608
|
-
timestamp > now ? "Webhook timestamp is too far in the future" : "Webhook timestamp is too old"
|
|
1609
|
-
);
|
|
1610
|
-
}
|
|
1611
|
-
let keyBytes;
|
|
1612
|
-
const base64Part = secret.startsWith(WHSEC_PREFIX) ? secret.slice(WHSEC_PREFIX.length) : secret;
|
|
1613
|
-
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Part) || base64Part.length === 0) {
|
|
1614
|
-
throw new WebhookVerificationError("Invalid signing secret: could not base64-decode");
|
|
1615
|
-
}
|
|
1616
|
-
try {
|
|
1617
|
-
keyBytes = Buffer.from(base64Part, "base64");
|
|
1618
|
-
if (keyBytes.length === 0) {
|
|
1619
|
-
throw new Error("empty key");
|
|
1620
|
-
}
|
|
1621
|
-
} catch {
|
|
1622
|
-
throw new WebhookVerificationError("Invalid signing secret: could not base64-decode");
|
|
1623
|
-
}
|
|
1624
|
-
const bodyStr = typeof body === "string" ? body : Buffer.from(body).toString("utf-8");
|
|
1625
|
-
const signedContent = `${webhookId}.${timestampStr}.${bodyStr}`;
|
|
1626
|
-
const expectedSig = createHmac("sha256", keyBytes).update(signedContent).digest("base64");
|
|
1627
|
-
const candidates = signatureHeader.split(" ");
|
|
1628
|
-
for (const candidate of candidates) {
|
|
1629
|
-
if (!candidate.startsWith("v1,")) continue;
|
|
1630
|
-
const candidateSig = candidate.slice(3);
|
|
1631
|
-
const expectedBuf = Buffer.from(expectedSig, "utf-8");
|
|
1632
|
-
const candidateBuf = Buffer.from(candidateSig, "utf-8");
|
|
1633
|
-
if (expectedBuf.length !== candidateBuf.length) continue;
|
|
1634
|
-
if (timingSafeEqual(expectedBuf, candidateBuf)) {
|
|
1635
|
-
try {
|
|
1636
|
-
return JSON.parse(bodyStr);
|
|
1637
|
-
} catch {
|
|
1638
|
-
throw new WebhookVerificationError("Webhook signature is valid but body is not valid JSON");
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
throw new WebhookVerificationError(
|
|
1643
|
-
"Webhook signature does not match \u2014 ensure you are using the raw request body"
|
|
1644
|
-
);
|
|
1645
|
-
}
|
|
1646
|
-
|
|
1647
|
-
// src/types/transactions.ts
|
|
1648
|
-
var TransactionTypeFilter = /* @__PURE__ */ ((TransactionTypeFilter2) => {
|
|
1649
|
-
TransactionTypeFilter2["PAYMENT"] = "payment";
|
|
1650
|
-
TransactionTypeFilter2["TRANSFER"] = "transfer";
|
|
1651
|
-
TransactionTypeFilter2["ALL"] = "all";
|
|
1652
|
-
return TransactionTypeFilter2;
|
|
1653
|
-
})(TransactionTypeFilter || {});
|
|
1654
|
-
|
|
1655
|
-
export { AuthenticationError, InsufficientFundsError, InvalidRequestError, NaturalClient, NaturalError, PaymentError, RateLimitError, RecipientNotFoundError, ServerError, TransactionTypeFilter, VERSION, WebhookVerificationError, agentConfigToDict, bindContext, clearContext, configHash, configureLogging, generateToolCallId, getContext, getLogger, getToolCallHeader, logApiCall, logError, logToolCall, modelUsageToDict, parseApiKeyEnv, runWithContext, runWithToolCall, validateBaseUrl, verifyWebhookSignature };
|
|
1656
|
-
//# sourceMappingURL=index.js.map
|
|
1657
|
-
//# sourceMappingURL=index.js.map
|