@dakota-xyz/ts-sdk 1.6.0 → 2.1.0

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/dist/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { randomUUID, generateKeyPairSync, createPrivateKey, createPublicKey, createSign, createVerify } from 'crypto';
2
+
1
3
  // src/client/environment.ts
2
4
  var Environment = /* @__PURE__ */ ((Environment2) => {
3
5
  Environment2["Sandbox"] = "sandbox";
@@ -227,7 +229,7 @@ function resolveConfig(config) {
227
229
  // src/client/transport.ts
228
230
  var RETRYABLE_STATUS_CODES2 = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
229
231
  var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
230
- var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
232
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
231
233
  var Transport = class {
232
234
  config;
233
235
  constructor(config) {
@@ -674,12 +676,87 @@ var CustomersResource = class extends BaseResource {
674
676
  path: `/customers/${customerId}`
675
677
  });
676
678
  }
679
+ /**
680
+ * Delete a customer record.
681
+ *
682
+ * Soft-deletes the customer. Blocked with a 409 if the customer still has
683
+ * associated accounts, or is referenced as a sub-client by another customer.
684
+ *
685
+ * @param customerId - Customer ID (KSUID)
686
+ *
687
+ * @example
688
+ * ```typescript
689
+ * await client.customers.delete('cust_abc123');
690
+ * ```
691
+ */
692
+ async delete(customerId) {
693
+ await this.transport.request({
694
+ method: "DELETE",
695
+ path: `/customers/${customerId}`
696
+ });
697
+ }
698
+ /**
699
+ * List a customer's capabilities and what is still needed to unlock each.
700
+ *
701
+ * Returns the customer's rails (e.g. `international_wire`) with a status and
702
+ * the OUTSTANDING requirements — terms to accept, documents to upload — that
703
+ * gate them. Partner-agnostic: requirements are keyed by an opaque terms id
704
+ * or document type, never a provider or partner name.
705
+ *
706
+ * @param customerId - Customer ID (KSUID)
707
+ * @returns The customer's capabilities and their outstanding requirements
708
+ *
709
+ * @example
710
+ * ```typescript
711
+ * const { capabilities } = await client.customers.getCapabilities(customerId);
712
+ * for (const cap of capabilities) {
713
+ * if (cap.status !== 'action_required') continue;
714
+ * for (const req of cap.requirements) {
715
+ * console.log(`${cap.capability}: ${req.title} → ${req.url}`);
716
+ * }
717
+ * }
718
+ * ```
719
+ */
720
+ async getCapabilities(customerId) {
721
+ return this.transport.request({
722
+ method: "GET",
723
+ path: `/customers/${customerId}/capabilities`
724
+ });
725
+ }
726
+ /**
727
+ * Mint a fresh application link for re-engaging an APPROVED customer.
728
+ *
729
+ * Issues a new onboarding token for an existing approved customer's
730
+ * application and returns the rebuilt `application_url` — use it when the
731
+ * original token has expired and the customer needs to come back through
732
+ * the hosted flow (e.g. to accept outstanding partner disclosures).
733
+ *
734
+ * @param customerId - Customer ID (KSUID)
735
+ * @param options - Request options (e.g., custom idempotency key)
736
+ * @returns The rebuilt application URL
737
+ *
738
+ * @example
739
+ * ```typescript
740
+ * const { application_url } = await client.customers.reEngage(customerId);
741
+ * ```
742
+ */
743
+ async reEngage(customerId, options) {
744
+ return this.transport.request({
745
+ method: "POST",
746
+ path: `/customers/${customerId}/re-engagement`,
747
+ idempotencyKey: options?.idempotencyKey
748
+ });
749
+ }
677
750
  /**
678
751
  * Update the sub-client association for a customer.
679
752
  *
680
753
  * Associates or disassociates a customer with a sub-client.
681
754
  * Set `sub_client_id` to associate, or set it to `null` to disassociate.
682
755
  *
756
+ * @deprecated The sub-client association can only be set when a customer is
757
+ * created (`is_sub_client` / `sub_client_id` on `create`) and can no longer
758
+ * be changed afterwards — this endpoint now returns 400.
759
+ *
683
760
  * @param customerId - Customer ID (KSUID)
684
761
  * @param data - Sub-client association data
685
762
  * @param options - Request options (e.g., custom idempotency key)
@@ -756,6 +833,93 @@ var CustomersResource = class extends BaseResource {
756
833
  idempotencyKey: options?.idempotencyKey
757
834
  });
758
835
  }
836
+ /**
837
+ * Import customers from Persona Connect share tokens (`cnst_...`).
838
+ *
839
+ * Unlike the Sumsub import, Persona redemption is asynchronous on Persona's
840
+ * side, so this returns a JOB immediately (HTTP 202). Poll
841
+ * `getPersonaImportJob` for per-token results. Up to 5,000 tokens per
842
+ * request — split larger migrations into multiple batches.
843
+ *
844
+ * Tokens are validated and de-duplicated up front, and a skipped token
845
+ * never blocks an accepted one. A `skipped` entry is about the token STRING
846
+ * (malformed, duplicated in the batch, or already imported) — it is never a
847
+ * compliance decision about a person or application.
848
+ *
849
+ * @param data - The share tokens to import
850
+ * @param options - Request options (e.g., custom idempotency key)
851
+ * @returns The queued job, with any tokens that could not be enqueued
852
+ *
853
+ * @example
854
+ * ```typescript
855
+ * const job = await client.customers.importPersonaTokens({
856
+ * tokens: ['cnst_ABC123def456', 'cnst_GHI789jkl012'],
857
+ * });
858
+ * console.log(`${job.accepted}/${job.total} queued as ${job.job_id}`);
859
+ * ```
860
+ */
861
+ async importPersonaTokens(data, options) {
862
+ return this.transport.request({
863
+ method: "POST",
864
+ path: "/customers/import-persona-tokens",
865
+ body: data,
866
+ idempotencyKey: options?.idempotencyKey
867
+ });
868
+ }
869
+ /**
870
+ * List this client's Persona share-token import jobs, newest first.
871
+ *
872
+ * This endpoint pages on its own cursor (`starting_after` + `has_more`), not
873
+ * the standard list envelope, so it returns a single page rather than an
874
+ * async iterator.
875
+ *
876
+ * @param params - Optional `limit` and `starting_after` job-id cursor
877
+ * @returns One page of job summaries plus a `has_more` flag
878
+ *
879
+ * @example
880
+ * ```typescript
881
+ * const { jobs, has_more } = await client.customers.listPersonaImportJobs({ limit: 20 });
882
+ * ```
883
+ */
884
+ async listPersonaImportJobs(params) {
885
+ return this.transport.request({
886
+ method: "GET",
887
+ path: "/customers/persona-import-jobs",
888
+ query: { ...params }
889
+ });
890
+ }
891
+ /**
892
+ * Get a Persona import job's status and its per-token results.
893
+ *
894
+ * Result rows page on a row-index cursor: pass the last row's `index` as
895
+ * `results_after_index` while `has_more_results` is true.
896
+ *
897
+ * @param jobId - Import job ID (`pij_...`)
898
+ * @param params - Optional `results_limit` (1-500) and `results_after_index`
899
+ * @returns Job status, row counts, and one page of result rows
900
+ *
901
+ * @example
902
+ * ```typescript
903
+ * let after: number | undefined;
904
+ * do {
905
+ * const job = await client.customers.getPersonaImportJob(jobId, {
906
+ * results_after_index: after,
907
+ * });
908
+ * for (const row of job.results ?? []) {
909
+ * if (row.state === 'failed') console.error(row.token, row.error);
910
+ * after = row.index;
911
+ * }
912
+ * if (!job.has_more_results) break;
913
+ * } while (true);
914
+ * ```
915
+ */
916
+ async getPersonaImportJob(jobId, params) {
917
+ return this.transport.request({
918
+ method: "GET",
919
+ path: `/customers/persona-import-jobs/${jobId}`,
920
+ query: { ...params }
921
+ });
922
+ }
759
923
  };
760
924
 
761
925
  // src/client/resources/recipients.ts
@@ -1520,8 +1684,18 @@ var ApplicationsResource = class extends BaseResource {
1520
1684
  /**
1521
1685
  * Submit an attestation for an application.
1522
1686
  *
1687
+ * Additionally supplying `disclosure_id` (a terms key the provider
1688
+ * declared, e.g. `partner_disclosures`) and `disclosure_version` records the
1689
+ * attestation as a PARTNER DISCLOSURE acknowledgment instead of a standard
1690
+ * onboarding one: acceptance is stamped `customer_online`, the
1691
+ * partner-onboarding substatus advances, and an already-approved
1692
+ * application is reprovisioned. The API stays partner-agnostic — callers
1693
+ * supply a terms key and version, never a partner name. Get the outstanding
1694
+ * ones from `customers.getCapabilities(customerId)`.
1695
+ *
1523
1696
  * @param applicationId - Application ID
1524
- * @param data - Attestation data (type, timestamp, applicant_id)
1697
+ * @param data - Attestation data (type, timestamp, applicant_id), plus
1698
+ * `disclosure_id` + `disclosure_version` to accept a partner disclosure
1525
1699
  */
1526
1700
  async submitAttestation(applicationId, data, options) {
1527
1701
  await this.transport.request({
@@ -1893,21 +2067,39 @@ var SignerGroupsResource = class extends BaseResource {
1893
2067
  /**
1894
2068
  * Get a signer group by ID.
1895
2069
  *
2070
+ * Pass `{ include_removed: true }` to also get a `removed_members` array of
2071
+ * signers that were removed from this group, each carrying its `removed_at`
2072
+ * timestamp. Defaults to active members only.
2073
+ *
1896
2074
  * @param signerGroupId - Signer group ID
2075
+ * @param params - Optional `{ include_removed }`
1897
2076
  * @returns Signer group record
2077
+ *
2078
+ * @example
2079
+ * ```typescript
2080
+ * const group = await client.signerGroups.get(groupId, { include_removed: true });
2081
+ * for (const s of group.removed_members ?? []) {
2082
+ * console.log(s.name, 'removed at', s.removed_at);
2083
+ * }
2084
+ * ```
1898
2085
  */
1899
- async get(signerGroupId) {
2086
+ async get(signerGroupId, params) {
1900
2087
  return this.transport.request({
1901
2088
  method: "GET",
1902
- path: `/signer-groups/${signerGroupId}`
2089
+ path: `/signer-groups/${signerGroupId}`,
2090
+ query: { ...params }
1903
2091
  });
1904
2092
  }
1905
2093
  /**
1906
- * Add a signer to a group.
2094
+ * Add an existing signer's public key to a group.
2095
+ *
2096
+ * The endpoint takes `{ member_key }` — the base64 PKIX (SPKI) public
2097
+ * key of an existing signer resource — not a fresh signer definition.
2098
+ * Returns the updated group (with the new member included).
1907
2099
  *
1908
2100
  * @param signerGroupId - Signer group ID
1909
- * @param data - Signer creation data
1910
- * @returns Created signer
2101
+ * @param data - `{ member_key }` (the signer's base64 PKIX public key)
2102
+ * @returns The updated signer group
1911
2103
  */
1912
2104
  async addSigner(signerGroupId, data, options) {
1913
2105
  return this.transport.request({
@@ -1921,12 +2113,16 @@ var SignerGroupsResource = class extends BaseResource {
1921
2113
  * Remove a signer from a group.
1922
2114
  *
1923
2115
  * @param signerGroupId - Signer group ID
1924
- * @param signerId - Signer ID
2116
+ * @param signerId - The signer's KSUID `signer_id` — NOT its public key.
2117
+ * (The standalone `client.signers.delete()` takes the public key instead.)
2118
+ * @param options - Optional request options (e.g. an explicit idempotency
2119
+ * key — the platform requires one on this DELETE)
1925
2120
  */
1926
- async removeSigner(signerGroupId, signerId) {
2121
+ async removeSigner(signerGroupId, signerId, options) {
1927
2122
  await this.transport.request({
1928
2123
  method: "DELETE",
1929
- path: `/signer-groups/${signerGroupId}/signers/${signerId}`
2124
+ path: `/signer-groups/${signerGroupId}/signers/${signerId}`,
2125
+ idempotencyKey: options?.idempotencyKey
1930
2126
  });
1931
2127
  }
1932
2128
  /**
@@ -2623,6 +2819,650 @@ var SelfServeResource = class extends BaseResource {
2623
2819
  }
2624
2820
  };
2625
2821
 
2822
+ // src/client/resources/fee-payout-destination.ts
2823
+ var FeePayoutDestinationResource = class extends BaseResource {
2824
+ /**
2825
+ * Get the destination registered to receive your developer-fee payouts.
2826
+ *
2827
+ * @returns The registered destination
2828
+ *
2829
+ * @example
2830
+ * ```typescript
2831
+ * const dest = await client.feePayoutDestination.get();
2832
+ * console.log(dest.chain, dest.wallet_address);
2833
+ * ```
2834
+ */
2835
+ async get() {
2836
+ return this.transport.request({
2837
+ method: "GET",
2838
+ path: "/fee-payout-destination"
2839
+ });
2840
+ }
2841
+ /**
2842
+ * Register or replace your fee payout destination.
2843
+ *
2844
+ * There is exactly one destination per organization, so this REPLACES any
2845
+ * existing one. Emits `fee_payout_destination.updated`.
2846
+ *
2847
+ * `chain` is a CAIP-2 chain id (e.g. `eip155:8453`) from the supported
2848
+ * networks list — see `client.info.getNetworks()`.
2849
+ *
2850
+ * @param data - The USDC wallet to pay fees to
2851
+ * @param options - Request options (e.g., custom idempotency key)
2852
+ * @returns The stored destination
2853
+ *
2854
+ * @example
2855
+ * ```typescript
2856
+ * const dest = await client.feePayoutDestination.set({
2857
+ * usdc_wallet: {
2858
+ * chain: 'eip155:8453',
2859
+ * address: '0x1234567890123456789012345678901234567890',
2860
+ * },
2861
+ * });
2862
+ * ```
2863
+ */
2864
+ async set(data, options) {
2865
+ return this.transport.request({
2866
+ method: "PUT",
2867
+ path: "/fee-payout-destination",
2868
+ body: data,
2869
+ idempotencyKey: options?.idempotencyKey
2870
+ });
2871
+ }
2872
+ /**
2873
+ * Remove the registered fee payout destination, if one exists.
2874
+ *
2875
+ * Emits `fee_payout_destination.deleted`.
2876
+ *
2877
+ * @example
2878
+ * ```typescript
2879
+ * await client.feePayoutDestination.delete();
2880
+ * ```
2881
+ */
2882
+ async delete() {
2883
+ await this.transport.request({
2884
+ method: "DELETE",
2885
+ path: "/fee-payout-destination"
2886
+ });
2887
+ }
2888
+ };
2889
+
2890
+ // src/client/resources/payment-agents.ts
2891
+ var PaymentAgentsResource = class extends BaseResource {
2892
+ /**
2893
+ * Create a hosted payment agent.
2894
+ *
2895
+ * @param data - Payment agent creation data (customer_id, name, hosted)
2896
+ * @returns The created payment agent (id, signer_id, signer_public_key, state)
2897
+ */
2898
+ async create(data, options) {
2899
+ return this.transport.request({
2900
+ method: "POST",
2901
+ path: "/payment-agents",
2902
+ body: data,
2903
+ idempotencyKey: options?.idempotencyKey
2904
+ });
2905
+ }
2906
+ /**
2907
+ * Get a hosted payment agent.
2908
+ *
2909
+ * Returns the agent together with the wallets it can currently spend
2910
+ * from. `wallet_ids` are DERIVED at query time from the agent signer's
2911
+ * live signer-group membership, so they reflect the agent's access
2912
+ * right now — not just at creation time.
2913
+ *
2914
+ * @param paymentAgentId - Payment agent ID
2915
+ */
2916
+ async get(paymentAgentId) {
2917
+ return this.transport.request({
2918
+ method: "GET",
2919
+ path: `/payment-agents/${paymentAgentId}`
2920
+ });
2921
+ }
2922
+ /**
2923
+ * Revoke a hosted payment agent.
2924
+ *
2925
+ * The agent can no longer be used, and its signing key is destroyed
2926
+ * in the isolated signer service (best-effort — the revoked state is
2927
+ * authoritative). Idempotent.
2928
+ *
2929
+ * The response's `signer_group_cleanup` names the signer groups the
2930
+ * (now-revoked) agent's signer still belongs to. A revoked signer can't
2931
+ * sign, but its group membership lingers — remove it with
2932
+ * `client.signerGroups.removeSigner(signer_group_id, signer_id)` to
2933
+ * finish de-provisioning.
2934
+ *
2935
+ * @param paymentAgentId - Payment agent ID
2936
+ * @returns The revoked payment agent (state=revoked, signer_group_cleanup?)
2937
+ */
2938
+ async revoke(paymentAgentId, options) {
2939
+ return this.transport.request({
2940
+ method: "POST",
2941
+ path: `/payment-agents/${paymentAgentId}/revoke`,
2942
+ idempotencyKey: options?.idempotencyKey
2943
+ });
2944
+ }
2945
+ /**
2946
+ * Draft payment proposals from a conversation.
2947
+ *
2948
+ * Pure cognition, no side effects: turn a customer's natural-language
2949
+ * request into reviewable proposals. Stateless — send the whole
2950
+ * conversation so far in `messages` on each call. Prefer
2951
+ * `AgentConversation` for multi-turn chat; use this directly only for
2952
+ * one-shot proposals.
2953
+ *
2954
+ * @param paymentAgentId - Payment agent ID
2955
+ * @param data - Prompt and/or messages
2956
+ * @returns Proposals (at high confidence) and/or a conversational reply
2957
+ */
2958
+ async createProposals(paymentAgentId, data, options) {
2959
+ return this.transport.request({
2960
+ method: "POST",
2961
+ path: `/payment-agents/${paymentAgentId}/proposals`,
2962
+ body: data,
2963
+ idempotencyKey: options?.idempotencyKey
2964
+ });
2965
+ }
2966
+ /**
2967
+ * Live progress of an in-flight drafting turn.
2968
+ *
2969
+ * A multi-payee drafting turn legitimately runs minutes (several sequential
2970
+ * model calls). While a `createProposals` call is in flight, poll this every
2971
+ * few seconds to show the customer what the agent is doing right now.
2972
+ *
2973
+ * Advisory display only. `active: false` means no turn is currently
2974
+ * publishing progress for this agent — idle, just finished, or served by
2975
+ * another instance — so fall back to a generic spinner. Never gate any
2976
+ * behaviour on this endpoint.
2977
+ *
2978
+ * The snapshot is coarse and customer-safe: a phase enum, one human
2979
+ * sentence, and the model round. Tool counts only — never payee names,
2980
+ * amounts, or addresses.
2981
+ *
2982
+ * @param paymentAgentId - Payment agent ID
2983
+ * @returns The current progress snapshot
2984
+ *
2985
+ * @example
2986
+ * ```typescript
2987
+ * const pending = client.paymentAgents.createProposals(agentId, { prompt });
2988
+ * const poll = setInterval(async () => {
2989
+ * const p = await client.paymentAgents.getProposalsProgress(agentId);
2990
+ * if (p.active) console.log(p.detail);
2991
+ * }, 3000);
2992
+ * const result = await pending.finally(() => clearInterval(poll));
2993
+ * ```
2994
+ */
2995
+ async getProposalsProgress(paymentAgentId) {
2996
+ return this.transport.request({
2997
+ method: "GET",
2998
+ path: `/payment-agents/${paymentAgentId}/proposals/progress`
2999
+ });
3000
+ }
3001
+ };
3002
+
3003
+ // src/client/resources/instructions.ts
3004
+ var InstructionsResource = class extends BaseResource {
3005
+ /**
3006
+ * Accept proposals — actuate them into persisted instructions.
3007
+ *
3008
+ * @param data - The payment agent id and the proposals to accept
3009
+ * @returns instruction_ids + the mandates the batch drafted (in full
3010
+ * wire shape; sign the §8 approval immediately)
3011
+ */
3012
+ async create(data, options) {
3013
+ return this.transport.request({
3014
+ method: "POST",
3015
+ path: "/instructions",
3016
+ body: data,
3017
+ idempotencyKey: options?.idempotencyKey
3018
+ });
3019
+ }
3020
+ /**
3021
+ * Get an accepted instruction — its action series and the per-action
3022
+ * downstream artifacts actuation produced.
3023
+ *
3024
+ * @param instructionId - Instruction ID
3025
+ */
3026
+ async get(instructionId) {
3027
+ return this.transport.request({
3028
+ method: "GET",
3029
+ path: `/instructions/${instructionId}`
3030
+ });
3031
+ }
3032
+ };
3033
+
3034
+ // src/client/resources/mandates.ts
3035
+ var MandatesResource = class extends BaseResource {
3036
+ /**
3037
+ * List mandates (newest first), with the EFFECTIVE status — a pending or
3038
+ * active mandate past its valid_until reads "expired". Filter with
3039
+ * customer_id / signer_id / status; omit them all for the full collection.
3040
+ *
3041
+ * @param params - Optional pagination + filter parameters
3042
+ * @returns Async iterator of mandates
3043
+ */
3044
+ list(params) {
3045
+ return this.paginate("/mandates", params);
3046
+ }
3047
+ /**
3048
+ * Get a mandate — the signer it binds, its rule exactly as the customer
3049
+ * approves it, validity, and status.
3050
+ *
3051
+ * @param mandateId - Mandate ID
3052
+ */
3053
+ async get(mandateId) {
3054
+ return this.transport.request({
3055
+ method: "GET",
3056
+ path: `/mandates/${mandateId}`
3057
+ });
3058
+ }
3059
+ /**
3060
+ * Create a mandate directly.
3061
+ *
3062
+ * Drafts a PENDING mandate from a direct user interaction — no instruction
3063
+ * back-link. Exactly one binding form names the signer the mandate binds:
3064
+ * `payment_agent_id` (hosted convenience — binds that agent's signer and
3065
+ * anchors to the agent's customer), or `signer_id` together with
3066
+ * `customer_id` (any of the client's signers, BYO keys included). The rule
3067
+ * is the one the customer will approve (via `approve`, a recognized signer
3068
+ * other than the bound one, §8).
3069
+ *
3070
+ * @param data - One binding form + rule + optional validity window
3071
+ * @returns The drafted (pending) mandate
3072
+ */
3073
+ async create(data, options) {
3074
+ return this.transport.request({
3075
+ method: "POST",
3076
+ path: "/mandates",
3077
+ body: data,
3078
+ idempotencyKey: options?.idempotencyKey
3079
+ });
3080
+ }
3081
+ /**
3082
+ * Approve a mandate.
3083
+ *
3084
+ * A recognized signer OTHER than the bound one signs the mandate payload
3085
+ * (see `mandateSignPayload` + `MandateSigner`) to activate it; arms its
3086
+ * scheduled payments.
3087
+ *
3088
+ * @param mandateId - Mandate ID
3089
+ * @param data - Approver public key (base64 PKIX) + base64 ASN.1 signature
3090
+ */
3091
+ async approve(mandateId, data, options) {
3092
+ return this.transport.request({
3093
+ method: "POST",
3094
+ path: `/mandates/${mandateId}/approve`,
3095
+ body: data,
3096
+ idempotencyKey: options?.idempotencyKey
3097
+ });
3098
+ }
3099
+ /**
3100
+ * Cancel a mandate.
3101
+ *
3102
+ * Revokes a pending or active mandate. The canceller must be a recognized
3103
+ * signer OTHER than the bound one, with a valid signature over the mandate
3104
+ * payload — the bound signer can never mutate its own mandate.
3105
+ *
3106
+ * @param mandateId - Mandate ID
3107
+ * @param data - Signer public key (base64 PKIX) + base64 ASN.1 signature
3108
+ */
3109
+ async cancel(mandateId, data, options) {
3110
+ return this.transport.request({
3111
+ method: "POST",
3112
+ path: `/mandates/${mandateId}/cancel`,
3113
+ body: data,
3114
+ idempotencyKey: options?.idempotencyKey
3115
+ });
3116
+ }
3117
+ /**
3118
+ * Amend a mandate — append a new signed version of its rule.
3119
+ *
3120
+ * Carries a changed rule into force with ONE signature and WITHOUT resetting
3121
+ * the spend already made in the current window: usage accrues to the
3122
+ * MANDATE, so an agent that has spent 9,000 of a 10,000 monthly limit and is
3123
+ * amended to 20,000 has 11,000 left, not 20,000.
3124
+ *
3125
+ * The `rule` is stored and verified VERBATIM — this endpoint does not
3126
+ * normalize it. It must already be canonical: `window` present and non-empty
3127
+ * (send `'NONE'` for a lifetime window), `targets` as recipient ids rather
3128
+ * than payee names, and `asset` uppercase. `target_type`, `window`, `asset`
3129
+ * and `network_id` must also match the current version exactly; only the
3130
+ * amount fields and `targets` may differ. Anything else is a 400 naming the
3131
+ * offending field.
3132
+ *
3133
+ * Build `signature` from `mandateAmendSignPayload(mandate, version, rule)` —
3134
+ * the amend payload commits to the version being created, so a signature for
3135
+ * v2 can never be replayed to append v3.
3136
+ *
3137
+ * @param mandateId - Mandate ID
3138
+ * @param data - Amending signer public key + signature + the complete NEW rule
3139
+ * @returns The mandate at its new current version
3140
+ *
3141
+ * @example
3142
+ * ```typescript
3143
+ * const mandate = await client.mandates.get(mandateId);
3144
+ * const nextVersion = (mandate.version ?? 1) + 1;
3145
+ * const rule = { ...mandate.rule, max_amount_in_window: '20000' };
3146
+ * const payload = mandateAmendSignPayload(mandate, nextVersion, rule);
3147
+ *
3148
+ * const amended = await client.mandates.amend(mandateId, {
3149
+ * signer_public_key: signer.publicKeyBase64(),
3150
+ * signature: await signer.sign(payload),
3151
+ * rule,
3152
+ * });
3153
+ * ```
3154
+ */
3155
+ async amend(mandateId, data, options) {
3156
+ return this.transport.request({
3157
+ method: "POST",
3158
+ path: `/mandates/${mandateId}/amend`,
3159
+ body: data,
3160
+ idempotencyKey: options?.idempotencyKey
3161
+ });
3162
+ }
3163
+ /**
3164
+ * List a mandate's versions, oldest first.
3165
+ *
3166
+ * The append-only history of every rule that was ever in force under this
3167
+ * mandate, and the §8 signer that put each one there. Versions are
3168
+ * immutable, so a rule listed here never changes — this is what makes an
3169
+ * executed payment's `mandate_version` audit stamp legible.
3170
+ *
3171
+ * @param mandateId - Mandate ID
3172
+ * @returns Every version, oldest first
3173
+ */
3174
+ async listVersions(mandateId) {
3175
+ return this.transport.request({
3176
+ method: "GET",
3177
+ path: `/mandates/${mandateId}/versions`
3178
+ });
3179
+ }
3180
+ /**
3181
+ * Get a mandate's remaining budget right now.
3182
+ *
3183
+ * The mandate's `rule` gives the ceilings; this gives the CONSUMPTION — what
3184
+ * has already been spent, what is earmarked by scheduled payments that have
3185
+ * not fired yet, and therefore what is left. Read it before scheduling:
3186
+ * otherwise an over-budget payment is only discovered when the gate denies
3187
+ * it at its due date, days later, with the payee unpaid.
3188
+ *
3189
+ * Advisory — nothing here reserves budget, and the gate remains the
3190
+ * authority at fire time. Two things to honour when reading a line:
3191
+ * an ABSENT `remaining_amount` / `remaining_count` means "not capped", never
3192
+ * "nothing left"; a `remaining_amount` of `'?'` means the figure could not
3193
+ * be summed and MUST be treated as no headroom (the gate fails closed on the
3194
+ * same data).
3195
+ *
3196
+ * @param mandateId - Mandate ID
3197
+ * @returns Per-target and aggregate budget lines, as of a stated instant
3198
+ *
3199
+ * @example
3200
+ * ```typescript
3201
+ * const budget = await client.mandates.getBudget(mandateId);
3202
+ * for (const line of budget.aggregate) {
3203
+ * console.log(line.bucket, line.remaining_amount ?? 'uncapped');
3204
+ * }
3205
+ * ```
3206
+ */
3207
+ async getBudget(mandateId) {
3208
+ return this.transport.request({
3209
+ method: "GET",
3210
+ path: `/mandates/${mandateId}/budget`
3211
+ });
3212
+ }
3213
+ };
3214
+
3215
+ // src/client/resources/scheduled-payments.ts
3216
+ var ScheduledPaymentsResource = class extends BaseResource {
3217
+ /**
3218
+ * List scheduled payments (oldest due first).
3219
+ *
3220
+ * Narrow the collection with the optional customer_id, signer_id,
3221
+ * wallet_id, mandate_id, and status filters; omit them all for the full
3222
+ * client collection.
3223
+ *
3224
+ * @param params - Optional pagination + filter parameters
3225
+ * @returns Async iterator of scheduled payments
3226
+ */
3227
+ list(params) {
3228
+ return this.paginate("/scheduled-payments", params);
3229
+ }
3230
+ /**
3231
+ * Schedule payments directly — bypass the proposal flow.
3232
+ *
3233
+ * Creates one or more scheduled payments for a signer under an existing
3234
+ * active mandate (coverage is matched at fire time, so no new signature
3235
+ * is needed here). The schedule is explicit `dates` OR `count` ×
3236
+ * `interval_seconds` from `start_at`.
3237
+ *
3238
+ * @param data - Signer + wallet + destination (or address+network_id) + schedule
3239
+ * @returns The rows that were created (one per date)
3240
+ */
3241
+ async create(data, options) {
3242
+ return this.transport.request({
3243
+ method: "POST",
3244
+ path: "/scheduled-payments",
3245
+ body: data,
3246
+ idempotencyKey: options?.idempotencyKey
3247
+ });
3248
+ }
3249
+ /**
3250
+ * Cancel one still-scheduled payment.
3251
+ *
3252
+ * Finalizes the row as cancelled. No signature is required — schedule rows
3253
+ * are bookkeeping, not authorization; the signed grant is the MANDATE,
3254
+ * which this does not touch.
3255
+ *
3256
+ * @param scheduledPaymentId - Scheduled payment ID
3257
+ */
3258
+ async cancel(scheduledPaymentId, options) {
3259
+ await this.transport.request({
3260
+ method: "POST",
3261
+ path: `/scheduled-payments/${scheduledPaymentId}/cancel`,
3262
+ idempotencyKey: options?.idempotencyKey
3263
+ });
3264
+ }
3265
+ };
3266
+
3267
+ // src/client/resources/insights.ts
3268
+ var InsightsResource = class extends BaseResource {
3269
+ /**
3270
+ * Get the customer's account insight report.
3271
+ *
3272
+ * A deterministic, read-only report: a snapshot of typed facts
3273
+ * (funding-wallet balances, upcoming totals, open payments, active
3274
+ * mandates), observations (`insights`), and advisory recommendations
3275
+ * (`suggestions`). Every item carries `evidence` — typed references to
3276
+ * the platform objects it was computed from. `kind` is an OPEN set;
3277
+ * ignore kinds you do not recognize.
3278
+ *
3279
+ * @param customerId - Customer ID
3280
+ * @returns The customer's insight report
3281
+ */
3282
+ async get(customerId) {
3283
+ return this.transport.request({
3284
+ method: "GET",
3285
+ path: `/customers/${customerId}/insights`
3286
+ });
3287
+ }
3288
+ /**
3289
+ * Ask about the customer's account.
3290
+ *
3291
+ * A read-only, advisory conversation. Stateless: send the conversation so
3292
+ * far in `messages` on each call; the response is the assistant's next
3293
+ * plain-text `reply`. The assistant narrates the same deterministic report
3294
+ * {@link get} returns — it never originates a number, never proposes, and
3295
+ * never moves money. Rate-limited per customer (hourly burst + daily
3296
+ * window) — a 429 means back off and retry later.
3297
+ *
3298
+ * @param customerId - Customer ID
3299
+ * @param data - The conversation so far (1–40 messages)
3300
+ * @returns The assistant's reply (+ how the boundary screen treated the turn)
3301
+ */
3302
+ async chat(customerId, data, options) {
3303
+ return this.transport.request({
3304
+ method: "POST",
3305
+ path: `/customers/${customerId}/insights/chat`,
3306
+ body: data,
3307
+ idempotencyKey: options?.idempotencyKey
3308
+ });
3309
+ }
3310
+ };
3311
+
3312
+ // src/agentic/chat.ts
3313
+ var AgentConversation = class {
3314
+ client;
3315
+ paymentAgentId;
3316
+ timezone;
3317
+ history = [];
3318
+ constructor(client, paymentAgentId, history, options) {
3319
+ this.client = client;
3320
+ this.paymentAgentId = paymentAgentId;
3321
+ this.timezone = options?.timezone;
3322
+ if (history && history.length > 0) {
3323
+ this.history = history.map(cloneMessage);
3324
+ }
3325
+ }
3326
+ /**
3327
+ * Adds the user's message to the transcript, asks the agent, records the
3328
+ * agent's reply, and returns the turn. When `hasProposals` is true the
3329
+ * agent has drafted a reviewable action series; otherwise `reply` holds
3330
+ * its next question.
3331
+ *
3332
+ * On error the optimistic user turn is rolled back, so the caller may
3333
+ * retry the same call without duplicating it.
3334
+ */
3335
+ async send(userMessage) {
3336
+ return this.sendWithAttachments(userMessage);
3337
+ }
3338
+ /**
3339
+ * {@link send} with documents (e.g. an invoice PDF) attached to the user
3340
+ * turn for the agent to read and draft payments from. Same turn semantics
3341
+ * and rollback-on-error behavior as `send`. Attachments ride only on the
3342
+ * turn they are passed; the stateless transcript keeps the agent's text
3343
+ * reply, so a follow-up turn relies on that summary rather than re-sending
3344
+ * the document.
3345
+ */
3346
+ async sendWithAttachments(userMessage, attachments) {
3347
+ const hasAttachments = attachments !== void 0 && attachments.length > 0;
3348
+ this.history.push({
3349
+ role: "user",
3350
+ content: userMessage,
3351
+ ...hasAttachments ? { attachments } : {}
3352
+ });
3353
+ const messages = this.history.map(serializeMessage);
3354
+ if (hasAttachments) {
3355
+ const last = this.history[this.history.length - 1];
3356
+ if (last) {
3357
+ delete last.attachments;
3358
+ }
3359
+ }
3360
+ let result;
3361
+ try {
3362
+ result = await this.client.paymentAgents.createProposals(this.paymentAgentId, {
3363
+ messages,
3364
+ // Resent on EVERY turn — the endpoint is stateless, so a zone given
3365
+ // once would be forgotten on the next one.
3366
+ ...this.timezone ? { timezone: this.timezone } : {}
3367
+ });
3368
+ } catch (err) {
3369
+ this.history.pop();
3370
+ throw err;
3371
+ }
3372
+ const turn = {
3373
+ reply: result.reply ?? "",
3374
+ proposals: result.proposals ? [...result.proposals] : [],
3375
+ hasProposals: !!result.proposals && result.proposals.length > 0,
3376
+ conversationStatus: result.conversation_status ?? ""
3377
+ };
3378
+ let assistant = turn.reply;
3379
+ if (!assistant) {
3380
+ assistant = turn.hasProposals ? "(drafted proposals for your review)" : "(no reply)";
3381
+ }
3382
+ this.history.push({ role: "assistant", content: assistant });
3383
+ return turn;
3384
+ }
3385
+ /**
3386
+ * A copy of the full transcript so far. Persist this between requests in
3387
+ * a stateless backend and rebuild with
3388
+ * {@link DakotaClient.resumeAgentConversation}.
3389
+ */
3390
+ messages() {
3391
+ return this.history.map(cloneMessage);
3392
+ }
3393
+ };
3394
+ function cloneMessage(m) {
3395
+ const out = { role: m.role, content: m.content };
3396
+ if (m.attachments && m.attachments.length > 0) {
3397
+ out.attachments = m.attachments.map((a) => ({ ...a }));
3398
+ }
3399
+ return out;
3400
+ }
3401
+ function serializeMessage(m) {
3402
+ const out = { role: m.role, content: m.content };
3403
+ if (m.attachments && m.attachments.length > 0) {
3404
+ out.attachments = m.attachments.map((a) => {
3405
+ const document = {
3406
+ media_type: a.mediaType,
3407
+ data: Buffer.from(a.data).toString("base64")
3408
+ };
3409
+ if (a.filename) {
3410
+ document.filename = a.filename;
3411
+ }
3412
+ return { type: "document", document };
3413
+ });
3414
+ }
3415
+ return out;
3416
+ }
3417
+ async function attachUserToWallet(client, walletId, signerPublicKey, spendingGroupId, options) {
3418
+ if (!walletId || !signerPublicKey || !spendingGroupId) {
3419
+ throw new Error("walletId, signerPublicKey and spendingGroupId are all required");
3420
+ }
3421
+ await requireGroupOnWallet(client, walletId, spendingGroupId);
3422
+ const group = await client.signerGroups.get(spendingGroupId);
3423
+ for (const member of group.members ?? []) {
3424
+ if (member.public_key === signerPublicKey) {
3425
+ return { alreadyMember: true };
3426
+ }
3427
+ }
3428
+ await client.signerGroups.addSigner(
3429
+ spendingGroupId,
3430
+ { member_key: signerPublicKey },
3431
+ { idempotencyKey: options?.idempotencyKey ?? randomUUID() }
3432
+ );
3433
+ return { alreadyMember: false };
3434
+ }
3435
+ async function detachUserFromWallet(client, walletId, signerPublicKey, spendingGroupId, options) {
3436
+ if (!walletId || !signerPublicKey || !spendingGroupId) {
3437
+ throw new Error("walletId, signerPublicKey and spendingGroupId are all required");
3438
+ }
3439
+ await requireGroupOnWallet(client, walletId, spendingGroupId);
3440
+ const group = await client.signerGroups.get(spendingGroupId);
3441
+ let signerId = "";
3442
+ for (const member of group.members ?? []) {
3443
+ if (member.public_key === signerPublicKey) {
3444
+ signerId = member.id ?? "";
3445
+ break;
3446
+ }
3447
+ }
3448
+ if (!signerId) {
3449
+ return { wasMember: false };
3450
+ }
3451
+ await client.signerGroups.removeSigner(spendingGroupId, signerId, {
3452
+ idempotencyKey: options?.idempotencyKey ?? randomUUID()
3453
+ });
3454
+ return { wasMember: true };
3455
+ }
3456
+ async function requireGroupOnWallet(client, walletId, spendingGroupId) {
3457
+ const wallets = await client.signerGroups.getWallets(spendingGroupId);
3458
+ for (const w of wallets) {
3459
+ if (w.id === walletId) {
3460
+ return;
3461
+ }
3462
+ }
3463
+ throw new Error(`signer group ${spendingGroupId} is not attached to wallet ${walletId}`);
3464
+ }
3465
+
2626
3466
  // src/client/client.ts
2627
3467
  var DakotaClient = class {
2628
3468
  config;
@@ -2664,6 +3504,18 @@ var DakotaClient = class {
2664
3504
  sandbox;
2665
3505
  /** Self-Serve Credits API - manage prepaid transfer credits */
2666
3506
  selfServe;
3507
+ /** Fee Payout Destination API - where Dakota pays your accrued developer fees */
3508
+ feePayoutDestination;
3509
+ /** Payment Agents API (ALPHA) - hosted signing agents that draft payments */
3510
+ paymentAgents;
3511
+ /** Instructions API (ALPHA) - accept and inspect actuated proposals */
3512
+ instructions;
3513
+ /** Mandates API (ALPHA) - the §8 authorizations that arm scheduled payments */
3514
+ mandates;
3515
+ /** Scheduled Payments API (ALPHA) - schedule rows created from instructions */
3516
+ scheduledPayments;
3517
+ /** Insights API (ALPHA) - read-only advisory reporting over agentic activity */
3518
+ insights;
2667
3519
  /**
2668
3520
  * Create a new Dakota client.
2669
3521
  *
@@ -2717,6 +3569,61 @@ var DakotaClient = class {
2717
3569
  this.info = new InfoResource(this.transport);
2718
3570
  this.sandbox = new SandboxResource(this.transport);
2719
3571
  this.selfServe = new SelfServeResource(this.transport);
3572
+ this.feePayoutDestination = new FeePayoutDestinationResource(this.transport);
3573
+ this.paymentAgents = new PaymentAgentsResource(this.transport);
3574
+ this.instructions = new InstructionsResource(this.transport);
3575
+ this.mandates = new MandatesResource(this.transport);
3576
+ this.scheduledPayments = new ScheduledPaymentsResource(this.transport);
3577
+ this.insights = new InsightsResource(this.transport);
3578
+ }
3579
+ // ==========================================================================
3580
+ // Agentic Payments high-level helpers (ALPHA)
3581
+ //
3582
+ // Collapse the multi-step, crypto-heavy hosted-agent flows into single
3583
+ // calls with good defaults. The raw operations remain reachable via
3584
+ // `signerGroups.addSigner` / `signerGroups.removeSigner` and friends.
3585
+ // ==========================================================================
3586
+ /**
3587
+ * Start a fresh multi-turn conversation with a payment agent.
3588
+ *
3589
+ * Pass `{ timezone }` (an IANA zone) so the agent resolves "tomorrow" and
3590
+ * "10 am" in the customer's local time rather than UTC. The conversation
3591
+ * resends it on every turn.
3592
+ *
3593
+ * @see AgentConversation
3594
+ */
3595
+ newAgentConversation(paymentAgentId, options) {
3596
+ return new AgentConversation(this, paymentAgentId, void 0, options);
3597
+ }
3598
+ /**
3599
+ * Rebuild a conversation from a persisted transcript (oldest first) —
3600
+ * for backends that store the history between requests.
3601
+ *
3602
+ * A stateless backend must pass `{ timezone }` again here: the transcript
3603
+ * carries the messages, not the zone.
3604
+ */
3605
+ resumeAgentConversation(paymentAgentId, history, options) {
3606
+ return new AgentConversation(this, paymentAgentId, history, options);
3607
+ }
3608
+ /**
3609
+ * Grant a principal (user or agent — both are just signers) permission to
3610
+ * spend from a wallet by adding its signer to an EXISTING signer group on
3611
+ * that wallet. Idempotent; errors if the group isn't attached to the wallet.
3612
+ *
3613
+ * @see attachUserToWallet in `agentic/wallets.ts` for the full contract.
3614
+ */
3615
+ attachUserToWallet(walletId, signerPublicKey, spendingGroupId, options) {
3616
+ return attachUserToWallet(this, walletId, signerPublicKey, spendingGroupId, options);
3617
+ }
3618
+ /**
3619
+ * Revoke a principal's spend permission by removing its signer from the
3620
+ * given signer group — the inverse of {@link attachUserToWallet}.
3621
+ * Idempotent; errors if the group isn't attached to the wallet.
3622
+ *
3623
+ * @see detachUserFromWallet in `agentic/wallets.ts` for the full contract.
3624
+ */
3625
+ detachUserFromWallet(walletId, signerPublicKey, spendingGroupId, options) {
3626
+ return detachUserFromWallet(this, walletId, signerPublicKey, spendingGroupId, options);
2720
3627
  }
2721
3628
  /**
2722
3629
  * Get the resolved base URL.
@@ -2726,6 +3633,249 @@ var DakotaClient = class {
2726
3633
  }
2727
3634
  };
2728
3635
 
2729
- export { APIError, AccountsResource, ApiKeysResource, ApplicationsResource, AuthMode, AutoTransactionsResource, ConfigurationError, CustomersResource, DEFAULT_RETRY_POLICY, DakotaClient, DestinationsResource, Environment, EventsResource, InfoResource, PaginatedIterator, PoliciesResource, RecipientsResource, SandboxResource, SelfServeResource, SignerGroupsResource, SignersResource, TransactionsResource, TransportError, UsersResource, WalletsResource, WebhooksResource, consoleLogger, getEnvironmentURL, noopLogger, paginate };
3636
+ // src/agentic/canonicalize.ts
3637
+ function canonicalJSON(value) {
3638
+ return canonicalize(value);
3639
+ }
3640
+ function canonicalize(value) {
3641
+ if (value === null || value === void 0) {
3642
+ return "null";
3643
+ }
3644
+ if (typeof value === "boolean") {
3645
+ return value ? "true" : "false";
3646
+ }
3647
+ if (typeof value === "number") {
3648
+ if (!Number.isFinite(value)) {
3649
+ throw new TypeError(`canonical JSON: non-finite number ${value}`);
3650
+ }
3651
+ return JSON.stringify(value);
3652
+ }
3653
+ if (typeof value === "string") {
3654
+ return JSON.stringify(value);
3655
+ }
3656
+ if (typeof value === "bigint") {
3657
+ throw new TypeError("canonical JSON: bigint values are not supported");
3658
+ }
3659
+ if (Array.isArray(value)) {
3660
+ const parts = value.map((item) => canonicalize(item));
3661
+ return `[${parts.join(",")}]`;
3662
+ }
3663
+ if (typeof value === "object") {
3664
+ const obj = value;
3665
+ const keys = Object.keys(obj).sort();
3666
+ const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);
3667
+ return `{${parts.join(",")}}`;
3668
+ }
3669
+ throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);
3670
+ }
3671
+
3672
+ // src/agentic/sign.ts
3673
+ function mandateSignPayload(mandate, action) {
3674
+ if (!mandate.id) {
3675
+ throw new Error("mandate has no id");
3676
+ }
3677
+ if (!mandate.bound_signer_id) {
3678
+ throw new Error("mandate has no bound_signer_id");
3679
+ }
3680
+ if (!mandate.rule) {
3681
+ throw new Error("mandate has no rule");
3682
+ }
3683
+ const encoded = canonicalJSON({
3684
+ action,
3685
+ id: mandate.id,
3686
+ bound_signer: mandate.bound_signer_id,
3687
+ rule: mandate.rule,
3688
+ valid_from: mandate.valid_from ?? 0,
3689
+ valid_until: mandate.valid_until ?? 0
3690
+ });
3691
+ return new TextEncoder().encode(encoded);
3692
+ }
3693
+ function mandateAmendSignPayload(mandate, version, rule) {
3694
+ if (!mandate.id) {
3695
+ throw new Error("mandate has no id");
3696
+ }
3697
+ if (!mandate.bound_signer_id) {
3698
+ throw new Error("mandate has no bound_signer_id");
3699
+ }
3700
+ if (!Number.isInteger(version) || version < 2) {
3701
+ throw new Error("amend version must be an integer >= 2 (the version being created)");
3702
+ }
3703
+ const encoded = canonicalJSON({
3704
+ action: "amend",
3705
+ id: mandate.id,
3706
+ bound_signer: mandate.bound_signer_id,
3707
+ rule,
3708
+ valid_from: mandate.valid_from ?? 0,
3709
+ valid_until: mandate.valid_until ?? 0,
3710
+ version
3711
+ });
3712
+ return new TextEncoder().encode(encoded);
3713
+ }
3714
+ function attachGroupPayload(walletId, groupId, idempotencyKey) {
3715
+ return textBytes(
3716
+ canonicalJSON({
3717
+ type: "attach_group_to_wallet",
3718
+ wallet_id: walletId,
3719
+ group_id: groupId,
3720
+ idempotency_key: idempotencyKey
3721
+ })
3722
+ );
3723
+ }
3724
+ function attachPolicyPayload(walletId, policyId, idempotencyKey) {
3725
+ return textBytes(
3726
+ canonicalJSON({
3727
+ type: "attach_policy_to_wallet",
3728
+ wallet_id: walletId,
3729
+ policy_id: policyId,
3730
+ idempotency_key: idempotencyKey
3731
+ })
3732
+ );
3733
+ }
3734
+ function detachGroupPayload(walletId, groupId, idempotencyKey) {
3735
+ return textBytes(
3736
+ canonicalJSON({
3737
+ type: "detach_group_from_wallet",
3738
+ wallet_id: walletId,
3739
+ group_id: groupId,
3740
+ idempotency_key: idempotencyKey
3741
+ })
3742
+ );
3743
+ }
3744
+ function detachPolicyPayload(walletId, policyId, idempotencyKey) {
3745
+ return textBytes(
3746
+ canonicalJSON({
3747
+ type: "detach_policy_from_wallet",
3748
+ wallet_id: walletId,
3749
+ policy_id: policyId,
3750
+ idempotency_key: idempotencyKey
3751
+ })
3752
+ );
3753
+ }
3754
+ function deletePolicyPayload(policyId, idempotencyKey) {
3755
+ return textBytes(
3756
+ canonicalJSON({
3757
+ type: "delete_policy",
3758
+ policy_id: policyId,
3759
+ idempotency_key: idempotencyKey
3760
+ })
3761
+ );
3762
+ }
3763
+ function removePolicyRulePayload(policyId, ruleId, idempotencyKey) {
3764
+ return textBytes(
3765
+ canonicalJSON({
3766
+ type: "remove_policy_rule",
3767
+ policy_id: policyId,
3768
+ rule_id: ruleId,
3769
+ idempotency_key: idempotencyKey
3770
+ })
3771
+ );
3772
+ }
3773
+ function updatePolicyRulePayload(policyId, ruleId, updatedDefinition, idempotencyKey) {
3774
+ return textBytes(
3775
+ canonicalJSON({
3776
+ type: "update_policy_rule",
3777
+ policy_id: policyId,
3778
+ rule_id: ruleId,
3779
+ updated_definition: updatedDefinition,
3780
+ idempotency_key: idempotencyKey
3781
+ })
3782
+ );
3783
+ }
3784
+ function addPolicyRulePayload(policyId, action, ruleType, definition, idempotencyKey) {
3785
+ return textBytes(
3786
+ canonicalJSON({
3787
+ type: "add_policy_rule",
3788
+ action,
3789
+ rule_type: ruleType,
3790
+ policy_id: policyId,
3791
+ definition,
3792
+ idempotency_key: idempotencyKey
3793
+ })
3794
+ );
3795
+ }
3796
+ function textBytes(s) {
3797
+ return new TextEncoder().encode(s);
3798
+ }
3799
+ var P256MandateSigner = class _P256MandateSigner {
3800
+ privateKey;
3801
+ publicKey;
3802
+ constructor(privateKey, publicKey) {
3803
+ this.privateKey = privateKey;
3804
+ this.publicKey = publicKey;
3805
+ }
3806
+ /**
3807
+ * Generate a fresh P-256 keypair.
3808
+ */
3809
+ static generate() {
3810
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
3811
+ return new _P256MandateSigner(privateKey, publicKey);
3812
+ }
3813
+ /**
3814
+ * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a
3815
+ * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.
3816
+ */
3817
+ static fromPrivateKey(key) {
3818
+ const privateKey = typeof key === "string" || key instanceof Uint8Array ? createPrivateKey({
3819
+ key,
3820
+ format: typeof key === "string" ? "pem" : "der",
3821
+ type: "pkcs8"
3822
+ }) : key;
3823
+ if (privateKey.asymmetricKeyType !== "ec") {
3824
+ throw new Error("a P-256 private key is required (ES256)");
3825
+ }
3826
+ const details = privateKey.asymmetricKeyDetails;
3827
+ if (details?.namedCurve !== "prime256v1") {
3828
+ throw new Error("a P-256 private key is required (ES256)");
3829
+ }
3830
+ const publicKey = createPublicKey(privateKey);
3831
+ return new _P256MandateSigner(privateKey, publicKey);
3832
+ }
3833
+ /**
3834
+ * base64 PKIX (SPKI) public key — pass this as the signer's registered
3835
+ * public key at agent creation / mandate approval.
3836
+ */
3837
+ publicKeyBase64() {
3838
+ const der = this.publicKey.export({ format: "der", type: "spki" });
3839
+ return Buffer.from(der).toString("base64");
3840
+ }
3841
+ /**
3842
+ * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).
3843
+ */
3844
+ sign(payload) {
3845
+ const signer = createSign("SHA256");
3846
+ signer.update(payload);
3847
+ const sig = signer.sign({ key: this.privateKey, dsaEncoding: "der" });
3848
+ return Buffer.from(sig).toString("base64");
3849
+ }
3850
+ };
3851
+ function verifyMandateSignature(publicKeyBase64, payload, signatureBase64) {
3852
+ let publicKey;
3853
+ try {
3854
+ publicKey = createPublicKey({
3855
+ key: Buffer.from(publicKeyBase64, "base64"),
3856
+ format: "der",
3857
+ type: "spki"
3858
+ });
3859
+ } catch (err) {
3860
+ throw new Error(`parse public key: ${err.message}`);
3861
+ }
3862
+ if (publicKey.asymmetricKeyType !== "ec") {
3863
+ throw new Error("not a P-256 public key (ES256 requires P-256)");
3864
+ }
3865
+ if (publicKey.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
3866
+ throw new Error("not a P-256 public key (ES256 requires P-256)");
3867
+ }
3868
+ const verifier = createVerify("SHA256");
3869
+ verifier.update(payload);
3870
+ const ok = verifier.verify(
3871
+ { key: publicKey, dsaEncoding: "der" },
3872
+ Buffer.from(signatureBase64, "base64")
3873
+ );
3874
+ if (!ok) {
3875
+ throw new Error("signature verification failed");
3876
+ }
3877
+ }
3878
+
3879
+ export { APIError, AccountsResource, AgentConversation, ApiKeysResource, ApplicationsResource, AuthMode, AutoTransactionsResource, ConfigurationError, CustomersResource, DEFAULT_RETRY_POLICY, DakotaClient, DestinationsResource, Environment, EventsResource, FeePayoutDestinationResource, InfoResource, InsightsResource, InstructionsResource, MandatesResource, P256MandateSigner, PaginatedIterator, PaymentAgentsResource, PoliciesResource, RecipientsResource, SandboxResource, ScheduledPaymentsResource, SelfServeResource, SignerGroupsResource, SignersResource, TransactionsResource, TransportError, UsersResource, WalletsResource, WebhooksResource, addPolicyRulePayload, attachGroupPayload, attachPolicyPayload, attachUserToWallet, canonicalJSON, consoleLogger, deletePolicyPayload, detachGroupPayload, detachPolicyPayload, detachUserFromWallet, getEnvironmentURL, mandateAmendSignPayload, mandateSignPayload, noopLogger, paginate, removePolicyRulePayload, updatePolicyRulePayload, verifyMandateSignature };
2730
3880
  //# sourceMappingURL=index.mjs.map
2731
3881
  //# sourceMappingURL=index.mjs.map