@provablehq/sdk 0.9.13 → 0.9.15-enc

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.
Files changed (35) hide show
  1. package/dist/mainnet/account.d.ts +15 -0
  2. package/dist/mainnet/browser.d.ts +5 -2
  3. package/dist/mainnet/browser.js +669 -160
  4. package/dist/mainnet/browser.js.map +1 -1
  5. package/dist/mainnet/constants.d.ts +1 -0
  6. package/dist/mainnet/integrations/sealance/merkle-tree.d.ts +63 -17
  7. package/dist/mainnet/models/cryptoBoxPubkey.d.ts +4 -0
  8. package/dist/mainnet/models/encryptedProvingRequest.d.ts +4 -0
  9. package/dist/mainnet/models/provingResponse.d.ts +48 -2
  10. package/dist/mainnet/models/record-scanner/encryptedRegistrationRequest.d.ts +8 -0
  11. package/dist/mainnet/models/record-scanner/registrationResult.d.ts +26 -0
  12. package/dist/mainnet/network-client.d.ts +77 -4
  13. package/dist/mainnet/node-polyfill.js +2 -49
  14. package/dist/mainnet/node-polyfill.js.map +1 -1
  15. package/dist/mainnet/node.js +2 -2
  16. package/dist/mainnet/record-scanner.d.ts +53 -5
  17. package/dist/mainnet/security.d.ts +38 -0
  18. package/dist/testnet/account.d.ts +15 -0
  19. package/dist/testnet/browser.d.ts +5 -2
  20. package/dist/testnet/browser.js +669 -160
  21. package/dist/testnet/browser.js.map +1 -1
  22. package/dist/testnet/constants.d.ts +1 -0
  23. package/dist/testnet/integrations/sealance/merkle-tree.d.ts +63 -17
  24. package/dist/testnet/models/cryptoBoxPubkey.d.ts +4 -0
  25. package/dist/testnet/models/encryptedProvingRequest.d.ts +4 -0
  26. package/dist/testnet/models/provingResponse.d.ts +48 -2
  27. package/dist/testnet/models/record-scanner/encryptedRegistrationRequest.d.ts +8 -0
  28. package/dist/testnet/models/record-scanner/registrationResult.d.ts +26 -0
  29. package/dist/testnet/network-client.d.ts +77 -4
  30. package/dist/testnet/node-polyfill.js +2 -49
  31. package/dist/testnet/node-polyfill.js.map +1 -1
  32. package/dist/testnet/node.js +2 -2
  33. package/dist/testnet/record-scanner.d.ts +53 -5
  34. package/dist/testnet/security.d.ts +38 -0
  35. package/package.json +4 -4
@@ -37,3 +37,4 @@ export declare const RECORD_DOMAIN = "RecordScannerV0";
37
37
  * Zero address on Aleo blockchain that corresponds to field element 0. Used as padding in Merkle trees and as a sentinel value.
38
38
  */
39
39
  export declare const ZERO_ADDRESS = "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc";
40
+ export declare const FIVE_MINUTES: number;
@@ -18,6 +18,7 @@ import { Field } from "../../wasm.js";
18
18
  * const proof_left = sealance.getSiblingPath(tree, leftIdx, 15);
19
19
  * const proof_right = sealance.getSiblingPath(tree, rightIdx, 15);
20
20
  * const exclusion_proof = [proof_left, proof_right];
21
+ * const formatted_proof = sealance.formatMerkleProof(exclusion_proof);
21
22
  * ```
22
23
  */
23
24
  declare class SealanceMerkleTree {
@@ -35,8 +36,9 @@ declare class SealanceMerkleTree {
35
36
  *
36
37
  * @example
37
38
  * ```typescript
39
+ * const sealance = new SealanceMerkleTree();
38
40
  * const address = "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px";
39
- * const fieldValue = convertAddressToField(address);
41
+ * const fieldValue = sealance.convertAddressToField(address);
40
42
  * console.log(fieldValue); // 123456789...n
41
43
  * ```
42
44
  */
@@ -59,16 +61,30 @@ declare class SealanceMerkleTree {
59
61
  *
60
62
  * @example
61
63
  * ```typescript
64
+ * const sealance = new SealanceMerkleTree();
62
65
  * const leaves = ["0field", "1field", "2field", "3field"];
63
- * const tree = buildTree(leaves);
66
+ * const tree = sealance.buildTree(leaves);
64
67
  * const root = tree[tree.length - 1]; // Get the Merkle root
65
68
  * ```
66
69
  */
67
70
  buildTree(leaves: string[]): bigint[];
68
- /** Converts an array of decimal string representations of U256 numbers to an array of BigInts.
71
+ /**
72
+ * Converts an array of decimal string representations of U256 numbers to an array of BigInts.
69
73
  *
70
74
  * @param tree - Array of decimal string representations of U256 numbers.
71
75
  * @returns Array of BigInts.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const treeStrings = ["0","4328470178059738374782465505490977516512210899136548187530607227309847251692","1741259420362056497457198439964202806733137875365061915996980524089960046336"];
80
+ * const sealance = new SealanceMerkleTree();
81
+ * const treeBigInts = sealance.convertTreeToBigInt(treeStrings);
82
+ * console.log(treeBigInts); // [
83
+ * 0,
84
+ * 4328470178059738374782465505490977516512210899136548187530607227309847251692,
85
+ * 1741259420362056497457198439964202806733137875365061915996980524089960046336
86
+ * ]
87
+ * ```
72
88
  */
73
89
  convertTreeToBigInt(tree: string[]): bigint[];
74
90
  /**
@@ -82,11 +98,18 @@ declare class SealanceMerkleTree {
82
98
  * @example
83
99
  * ```typescript
84
100
  * const addresses = [
85
- * "aleo1...",
86
- * "aleo1..."
87
- * ];
88
- * const leaves = generateLeaves(addresses, 15);
89
- * const tree = buildTree(leaves);
101
+ * "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px",
102
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
103
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
104
+ * ];
105
+ * const sealance = new SealanceMerkleTree();
106
+ * const leaves = sealance.generateLeaves(addresses, 15);
107
+ * console.log(leaves); // [
108
+ * "0field",
109
+ * "1295133970529764960316948294624974168921228814652993007266766481909235735940field",
110
+ * "1295133970529764960316948294624974168921228814652993007266766481909235735940field",
111
+ * "3501665755452795161867664882580888971213780722176652848275908626939553697821field"
112
+ * ]
90
113
  * ```
91
114
  */
92
115
  generateLeaves(addresses: string[], maxTreeDepth?: number): string[];
@@ -99,8 +122,15 @@ declare class SealanceMerkleTree {
99
122
  *
100
123
  * @example
101
124
  * ```typescript
102
- * const tree = buildTree(leaves);
103
- * const [leftIdx, rightIdx] = getLeafIndices(tree, "aleo1...");
125
+ * const addresses = [
126
+ * "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px",
127
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
128
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
129
+ * ];
130
+ * const sealance = new SealanceMerkleTree();
131
+ * const leaves = sealance.generateLeaves(addresses);
132
+ * const tree = sealance.buildTree(leaves);
133
+ * const [leftIdx, rightIdx] = sealance.getLeafIndices(tree, "aleo1...");
104
134
  * ```
105
135
  */
106
136
  getLeafIndices(merkleTree: bigint[], address: string): [number, number];
@@ -114,9 +144,17 @@ declare class SealanceMerkleTree {
114
144
  *
115
145
  * @example
116
146
  * ```typescript
117
- * const tree = buildTree(leaves);
118
- * const proof = getSiblingPath(tree, 0, 15);
119
- * // proof = { siblings: [0n, 1n, ...], leaf_index: 0 }
147
+ * const addresses = [
148
+ * "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px",
149
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
150
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
151
+ * ];
152
+ * const sealance = new SealanceMerkleTree();
153
+ * const leaves = sealance.generateLeaves(addresses);
154
+ * const tree = sealance.buildTree(leaves);
155
+ * const [leftIdx, rightIdx] = sealance.getLeafIndices(tree, "aleo1...");
156
+ * const proof = sealance.getSiblingPath(tree, leftIdx, 15);
157
+ * // proof = { siblings: [0n, 1n, ...], leaf_index: leftIdx }
120
158
  * ```
121
159
  */
122
160
  getSiblingPath(tree: bigint[], leafIndex: number, depth: number): {
@@ -131,10 +169,18 @@ declare class SealanceMerkleTree {
131
169
  *
132
170
  * @example
133
171
  * ```typescript
134
- * const tree = buildTree(leaves);
135
- * const proof = getSiblingPath(tree, 0, 15);
136
- * const proof2 = getSiblingPath(tree, 1, 15);
137
- * const formattedProof = formatMerkleProof([proof, proof2]);
172
+ * const addresses = [
173
+ * "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px",
174
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
175
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
176
+ * ];
177
+ * const sealance = new SealanceMerkleTree();
178
+ * const leaves = sealance.generateLeaves(addresses);
179
+ * const tree = sealance.buildTree(leaves);
180
+ * const [leftIdx, rightIdx] = sealance.getLeafIndices(tree, "aleo1...");
181
+ * const proof1 = getSiblingPath(tree, leftIdx, 15);
182
+ * const proof2 = getSiblingPath(tree, rightIdx, 15);
183
+ * const formattedProof = formatMerkleProof([proof1, proof2]);
138
184
  * // formattedProof = "[{ siblings: [0field, 1field, ...], leaf_index: 0u32 }, { siblings: [0field, 2field, ...], leaf_index: 1u32 }]"
139
185
  * ```
140
186
  */
@@ -0,0 +1,4 @@
1
+ export interface CryptoBoxPubKey {
2
+ key_id: string;
3
+ public_key: string;
4
+ }
@@ -0,0 +1,4 @@
1
+ export interface EncryptedProvingRequest {
2
+ key_id: string;
3
+ ciphertext: string;
4
+ }
@@ -1,5 +1,51 @@
1
- import { TransactionJSON } from "./transaction/transactionJSON";
1
+ import { TransactionJSON } from "./transaction/transactionJSON.js";
2
+ /** HTTP status and optional message from snarkOS broadcast (Accepted/Rejected variants). */
3
+ export interface BroadcastResponse {
4
+ status_code: bigint | number;
5
+ message?: string;
6
+ }
7
+ /** Result of the optional broadcast step. Discriminated by `status`. */
8
+ export type BroadcastResult = {
9
+ status: "Accepted";
10
+ status_code: bigint | number;
11
+ message?: string;
12
+ } | {
13
+ status: "Rejected";
14
+ status_code: bigint | number;
15
+ message?: string;
16
+ } | {
17
+ status: "Failed";
18
+ message: string;
19
+ } | {
20
+ status: "Skipped";
21
+ };
22
+ /** Success response body for POST /prove (HTTP 200). */
2
23
  export interface ProvingResponse {
3
24
  transaction: TransactionJSON;
4
- broadcast?: boolean;
25
+ broadcast_result: BroadcastResult;
26
+ }
27
+ /** Error response body for POST /prove (HTTP 400, 500, 503). Same shape for all error cases. */
28
+ export interface ProveApiErrorBody {
29
+ message: string;
30
+ }
31
+ /** Error thrown on prove API failure; `status` is set for retry logic (e.g. retryWithBackoff checks error.status >= 500). */
32
+ export interface ProvingRequestError extends Error {
33
+ status?: bigint | number;
34
+ }
35
+ /** Success variant of a proving request result. */
36
+ export interface ProvingSuccess {
37
+ ok: true;
38
+ data: ProvingResponse;
39
+ }
40
+ /** Failure variant of a proving request result (HTTP 400, 500, 503). */
41
+ export interface ProvingFailure {
42
+ ok: false;
43
+ status: bigint | number;
44
+ error: ProveApiErrorBody;
5
45
  }
46
+ /** Result of a proving request. Type used to give callers the ability to self-handle errors. */
47
+ export type ProvingResult = ProvingSuccess | ProvingFailure;
48
+ /** Type guard: value is a ProvingResponse. */
49
+ export declare function isProvingResponse(value: unknown): value is ProvingResponse;
50
+ /** Type guard: value is a ProveApiErrorBody. */
51
+ export declare function isProveApiErrorBody(value: unknown): value is ProveApiErrorBody;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Payload for the /register/encrypted record scanner endpoint.
3
+ * Contains the ephemeral key id and the sealed ciphertext of the registration request.
4
+ */
5
+ export interface EncryptedRegistrationRequest {
6
+ key_id: string;
7
+ ciphertext: string;
8
+ }
@@ -0,0 +1,26 @@
1
+ import type { RegistrationResponse } from "./registrationResponse.js";
2
+ /**
3
+ * Error thrown when a record scanner request fails (e.g. /register, /register/encrypted).
4
+ * Includes HTTP status so callers can handle 422 vs 500 etc.
5
+ */
6
+ export declare class RecordScannerRequestError extends Error {
7
+ readonly status: number;
8
+ constructor(message: string, status: number);
9
+ }
10
+ /** Error payload for registration failure result (/register and /register/encrypted). */
11
+ export interface RegistrationErrorBody {
12
+ message: string;
13
+ }
14
+ /** Success variant of registration result. */
15
+ export interface RegisterSuccess {
16
+ ok: true;
17
+ data: RegistrationResponse;
18
+ }
19
+ /** Failure variant of registration result. */
20
+ export interface RegisterFailure {
21
+ ok: false;
22
+ status: number;
23
+ error: RegistrationErrorBody;
24
+ }
25
+ /** Result of register() and registerEncrypted(); never throws on HTTP error. */
26
+ export type RegisterResult = RegisterSuccess | RegisterFailure;
@@ -3,7 +3,7 @@ import { BlockJSON } from "./models/blockJSON.js";
3
3
  import { TransactionJSON } from "./models/transaction/transactionJSON.js";
4
4
  import { Address, Plaintext, Program, ProvingRequest, RecordPlaintext, PrivateKey, Transaction } from "./wasm.js";
5
5
  import { ConfirmedTransactionJSON } from "./models/confirmed_transaction.js";
6
- import { ProvingResponse } from "./models/provingResponse.js";
6
+ import { ProvingResponse, ProvingResult } from "./models/provingResponse.js";
7
7
  type ProgramImports = {
8
8
  [key: string]: string | Program;
9
9
  };
@@ -11,18 +11,35 @@ interface AleoNetworkClientOptions {
11
11
  headers?: {
12
12
  [key: string]: string;
13
13
  };
14
+ proverUri?: string;
15
+ recordScannerUri?: string;
16
+ }
17
+ /**
18
+ * Interface for the JWT data.
19
+ *
20
+ * @property jwt {string} The JWT token string.
21
+ * @property expiration {number} The expiration time of the JWT token in UNIX timestamp format.
22
+ */
23
+ interface JWTData {
24
+ jwt: string;
25
+ expiration: number;
14
26
  }
15
27
  /**
16
28
  * Options for submitting a proving request.
17
29
  *
18
30
  * @property provingRequest {ProvingRequest | string} The proving request being submitted to the network.
19
31
  * @property url {string} The URL of the delegated proving service.
20
- * @property apiKey {string} The API key to use for authentication.
32
+ * @property apiKey {string} The API key used for generating a JWT.
33
+ * @property consumerId {string} The consumer ID associated with the API key.
34
+ * @property jwt {string} An optional JWT token used for authenticating with the proving service.
21
35
  */
22
36
  interface DelegatedProvingParams {
23
37
  provingRequest: ProvingRequest | string;
24
38
  url?: string;
25
39
  apiKey?: string;
40
+ consumerId?: string;
41
+ jwtData?: JWTData;
42
+ dpsPrivacy?: boolean;
26
43
  }
27
44
  /**
28
45
  * Client library that encapsulates REST calls to publicly exposed endpoints of Aleo nodes. The methods provided in this
@@ -35,6 +52,8 @@ interface DelegatedProvingParams {
35
52
  *
36
53
  * // Connection to a public beacon node
37
54
  * const account = Account.fromCiphertext(process.env.ciphertext, process.env.password);
55
+ * const apiKey = process.env.apiKey;
56
+ * const consumerId = process.env.consumerId;
38
57
  * const publicNetworkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined, account);
39
58
  */
40
59
  declare class AleoNetworkClient {
@@ -48,6 +67,11 @@ declare class AleoNetworkClient {
48
67
  };
49
68
  verboseErrors: boolean;
50
69
  readonly network: string;
70
+ apiKey?: string;
71
+ consumerId?: string;
72
+ jwtData?: JWTData;
73
+ proverUri?: string;
74
+ recordScannerUri?: string;
51
75
  constructor(host: string, options?: AleoNetworkClientOptions);
52
76
  /**
53
77
  * Set an account to use in networkClient calls
@@ -83,6 +107,36 @@ declare class AleoNetworkClient {
83
107
  * networkClient.setHost("http://api.explorer.provable.com/v1");
84
108
  */
85
109
  setHost(host: string): void;
110
+ /**
111
+ * Set a new uri for a remote prover.
112
+ *
113
+ * @param {string} proverUri The uri of the remote prover.
114
+ *
115
+ * @example
116
+ * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
117
+ *
118
+ * // Create a networkClient that connects to the provable explorer api.
119
+ * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
120
+ *
121
+ * // Set the prover uri.
122
+ * networkClient.setProverUri("https://prover.provable.prove");
123
+ */
124
+ setProverUri(proverUri: string): void;
125
+ /**
126
+ * Set a new uri for a remote record scanner.
127
+ *
128
+ * @param {string} recordScannerUri The uri of the remote record scanner.
129
+ *
130
+ * @example
131
+ * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
132
+ *
133
+ * // Create a networkClient that connects to the provable explorer api.
134
+ * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
135
+ *
136
+ * // Set the record scanner uri.
137
+ * networkClient.setRecordScannerUri("https://scanner.provable.scan");
138
+ */
139
+ setRecordScannerUri(recordScannerUri: string): void;
86
140
  /**
87
141
  * Set verbose errors to true or false for the `AleoNetworkClient`. When set to true, if `submitTransaction` fails, the failure responses will report descriptive information as to why the transaction failed.
88
142
  *
@@ -477,7 +531,7 @@ declare class AleoNetworkClient {
477
531
  * programImports = await networkClient.getProgramImports(double_test);
478
532
  * assert.deepStrictEqual(programImports, expectedImports);
479
533
  */
480
- getProgramImports(inputProgram: Program | string): Promise<ProgramImports>;
534
+ getProgramImports(inputProgram: Program | string, imports?: ProgramImports): Promise<ProgramImports>;
481
535
  /**
482
536
  * Get a list of the program names that a program imports.
483
537
  *
@@ -735,12 +789,31 @@ declare class AleoNetworkClient {
735
789
  */
736
790
  submitSolution(solution: string): Promise<string>;
737
791
  /**
738
- * Submit a `ProvingRequest` to a remote proving service for delegated proving. If the broadcast flag of the `ProvingRequest` is set to `true` the remote service will attempt to broadcast the result `Transaction` on behalf of the requestor.
792
+ * Refreshes the JWT by making a POST request to /jwts/{consumer_id}
793
+ *
794
+ * @param {string} apiKey - The API key for authentication.
795
+ * @param {string} consumerId - The consumer ID associated with the API key.
796
+ * @returns {Promise<JwtData>} The JWT token and expiration time
797
+ */
798
+ private refreshJwt;
799
+ /**
800
+ * Parses a /prove or /prove/encrypted response. Returns a result object (never throws for 200/400/500/503).
801
+ */
802
+ private handleProvingResponse;
803
+ /**
804
+ * Submit a `ProvingRequest` to a remote proving service for delegated proving. If the broadcast flag of the `ProvingRequest` is set to `true` the remote service will attempt to broadcast the result `Transaction` on behalf of the requestor. Throws on HTTP 400, 500, 503 (and retries on 500/503). Callers should {@link submitProvingRequestSafe} to handle proving request failures without throwing.
739
805
  *
740
806
  * @param {DelegatedProvingParams} options - The optional parameters required to submit a proving request.
741
807
  * @returns {Promise<ProvingResponse>} The ProvingResponse containing the transaction result and the result of the broadcast if the `broadcast` flag was set to `true`.
742
808
  */
743
809
  submitProvingRequest(options: DelegatedProvingParams): Promise<ProvingResponse>;
810
+ /**
811
+ * Submit a proving request and return a result object instead of throwing. This method is usable when callers want to handle HTTP status (400, 500, 503) yourself. Retries on 500/503 and returns on 200 or 400.
812
+ *
813
+ * @param {DelegatedProvingParams} options - The optional parameters required to submit a proving request.
814
+ * @returns {Promise<ProvingResult>} `{ ok: true, data }` on success (200), or `{ ok: false, status, error }` on 400/500/503. Check `result.ok` and then either `result.data` or `result.status` / `result.error.message`.
815
+ */
816
+ submitProvingRequestSafe(options: DelegatedProvingParams): Promise<ProvingResult>;
744
817
  /**
745
818
  * Await a submitted transaction to be confirmed or rejected on the Aleo network.
746
819
  *
@@ -3,7 +3,6 @@ import { webcrypto } from 'node:crypto';
3
3
  import * as $fs from 'node:fs';
4
4
  import $mime from 'mime/lite';
5
5
  import $xmlhttprequest from 'xmlhttprequest-ssl';
6
- import $request from 'sync-request';
7
6
  import * as $worker from 'node:worker_threads';
8
7
  import * as $os from 'node:os';
9
8
 
@@ -53,54 +52,8 @@ globalThis.fetch = async function (resource, options) {
53
52
  // @ts-ignore
54
53
  if (globalThis.XMLHttpRequest == null) {
55
54
  globalThis.XMLHttpRequest = class extends $xmlhttprequest.XMLHttpRequest {
56
- // We have to override the methods inside of the `constructor`
57
- // because `xmlhttprequest-ssl` doesn't use a regular class,
58
- // instead it defines all of the methods inside of the constructor.
59
- constructor(...args) {
60
- super(...args);
61
- const open = this.open;
62
- const send = this.send;
63
- let _async = true;
64
- let _url = null;
65
- let _mime = "text/xml";
66
- function reset() {
67
- _async = true;
68
- _url = null;
69
- _mime = "text/xml";
70
- }
71
- this.open = function (method, url, async, user, password) {
72
- // Special behavior for synchronous requests
73
- if (method === "GET" && !async && !user && !password) {
74
- _async = false;
75
- _url = url;
76
- // Default to the normal polyfill for async requests
77
- }
78
- else {
79
- reset();
80
- return open.call(this, method, url, async, user, password);
81
- }
82
- };
83
- this.send = function (data) {
84
- if (_async) {
85
- return send.call(this, data);
86
- // Use `sync-request` for synchronous requests.
87
- }
88
- else {
89
- const response = $request("GET", _url, {
90
- headers: {
91
- "Content-Type": _mime,
92
- }
93
- });
94
- const buffer = response.body.buffer;
95
- const responseText = new TextDecoder("iso-8859-5", { fatal: true }).decode(buffer);
96
- this.status = 200;
97
- this.response = this.responseText = responseText;
98
- reset();
99
- }
100
- };
101
- this.overrideMimeType = function (mime) {
102
- _mime = mime;
103
- };
55
+ constructor(opts) {
56
+ super({ syncPolicy: "enabled", ...opts });
104
57
  }
105
58
  };
106
59
  }
@@ -1 +1 @@
1
- {"version":3,"file":"node-polyfill.js","sources":["../../src/polyfill/crypto.ts","../../src/polyfill/fetch.ts","../../src/polyfill/xmlhttprequest.ts","../../src/polyfill/worker.ts","../../src/node-polyfill.ts"],"sourcesContent":["import { webcrypto } from \"node:crypto\";\n\nif ((globalThis as any).crypto == null) {\n (globalThis as any).crypto = webcrypto;\n}\n","import * as $fs from \"node:fs\";\nimport $mime from \"mime/lite\";\n\n\nconst oldFetch = globalThis.fetch;\n\n\nlet supports: Promise<boolean> | null = null;\n\nasync function checkFetch() {\n try {\n await oldFetch(new URL(\"file:\"));\n return true;\n\n } catch (e) {\n return false;\n }\n}\n\nasync function supportsFetch(): Promise<boolean> {\n if (supports === null) {\n supports = checkFetch();\n }\n\n return await supports;\n}\n\n\n// We always polyfill fetch because Node's fetch doesn't support file URLs.\n(globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise<Response> {\n const request = new Request(resource, options);\n\n const url = new URL(request.url);\n\n if (!(await supportsFetch()) && url.protocol === \"file:\") {\n const readStream = $fs.createReadStream(url);\n\n const headers: HeadersInit = {};\n\n const type = $mime.getType(url.pathname);\n\n if (type) {\n headers[\"Content-Type\"] = type;\n }\n\n return new Response(readStream as any, {\n status: 200,\n statusText: \"OK\",\n headers,\n });\n\n } else {\n return await oldFetch(request);\n }\n};\n","// @ts-ignore\nimport $xmlhttprequest from \"xmlhttprequest-ssl\";\nimport $request from \"sync-request\";\n\nif (globalThis.XMLHttpRequest == null) {\n globalThis.XMLHttpRequest = class extends $xmlhttprequest.XMLHttpRequest {\n // We have to override the methods inside of the `constructor`\n // because `xmlhttprequest-ssl` doesn't use a regular class,\n // instead it defines all of the methods inside of the constructor.\n constructor(...args: Array<any>) {\n super(...args);\n\n const open = (this as any).open;\n const send = (this as any).send;\n\n let _async: boolean = true;\n let _url: null | string = null;\n let _mime: string = \"text/xml\";\n\n function reset() {\n _async = true;\n _url = null;\n _mime = \"text/xml\";\n }\n\n (this as any).open = function (method: string, url: string, async: boolean, user?: string, password?: string) {\n // Special behavior for synchronous requests\n if (method === \"GET\" && !async && !user && !password) {\n _async = false;\n _url = url;\n\n // Default to the normal polyfill for async requests\n } else {\n reset();\n return open.call(this, method, url, async, user, password);\n }\n };\n\n (this as any).send = function (data: any) {\n if (_async) {\n return send.call(this, data);\n\n // Use `sync-request` for synchronous requests.\n } else {\n const response = $request(\"GET\", _url!, {\n headers: {\n \"Content-Type\": _mime,\n }\n });\n\n const buffer = (response.body as Buffer).buffer as any;\n\n const responseText = new TextDecoder(\"iso-8859-5\", { fatal: true }).decode(buffer);\n\n (this as any).status = 200;\n (this as any).response = (this as any).responseText = responseText;\n\n reset();\n }\n };\n\n (this as any).overrideMimeType = function (mime: string) {\n _mime = mime;\n };\n }\n } as any;\n}\n","import * as $worker from \"node:worker_threads\";\nimport * as $os from \"node:os\";\n\n// This is technically not a part of the Worker polyfill,\n// but Workers are used for multi-threading, so this is often\n// needed when writing Worker code.\nif (globalThis.navigator == null) {\n globalThis.navigator = {\n hardwareConcurrency: $os.cpus().length,\n } as Navigator;\n}\n\nif (globalThis.Worker == null) {\n globalThis.Worker = class Worker extends EventTarget {\n private _worker: import(\"node:worker_threads\").Worker;\n\n constructor(url: string | URL, options?: WorkerOptions | undefined) {\n super();\n\n if (url instanceof URL) {\n if (url.protocol !== \"file:\") {\n throw new Error(\"Worker only supports file: URLs\");\n }\n\n url = url.href;\n\n } else {\n throw new Error(\"Filepaths are unreliable, use `new URL(\\\"...\\\", import.meta.url)` instead.\");\n }\n\n if (!options || options.type !== \"module\") {\n throw new Error(\"Workers must use \\`type: \\\"module\\\"\\`\");\n }\n\n const code = `\n import(\"node:worker_threads\")\n .then(({ workerData }) => {\n return import(workerData.polyfill)\n .then(() => import(workerData.url))\n })\n .catch((e) => {\n // TODO maybe it should send a message to the parent?\n console.error(e.stack);\n });\n `;\n\n this._worker = new $worker.Worker(code, {\n eval: true,\n workerData: {\n url,\n polyfill: new URL(\"node-polyfill.js\", import.meta.url).href,\n },\n });\n\n this._worker.on(\"message\", (data) => {\n this.dispatchEvent(new MessageEvent(\"message\", { data }));\n });\n\n this._worker.on(\"messageerror\", (error) => {\n throw new Error(\"UNIMPLEMENTED\");\n });\n\n this._worker.on(\"error\", (error) => {\n // TODO attach the error to the event somehow\n const event = new Event(\"error\");\n this.dispatchEvent(event);\n });\n }\n\n set onmessage(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n set onmessageerror(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n set onerror(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n postMessage(message: any, transfer: Array<Transferable>): void;\n postMessage(message: any, options?: StructuredSerializeOptions | undefined): void;\n postMessage(value: any, transfer: any) {\n this._worker.postMessage(value, transfer);\n }\n\n terminate() {\n this._worker.terminate();\n }\n\n // This is Node-specific, it allows the process to exit\n // even if the Worker is still running.\n unref() {\n this._worker.unref();\n }\n };\n}\n\n\nif (!$worker.isMainThread) {\n const globals = globalThis as unknown as DedicatedWorkerGlobalScope;\n\n // This is used to create the onmessage, onmessageerror, and onerror setters\n const makeSetter = (prop: string, event: string) => {\n let oldvalue: () => void;\n\n Object.defineProperty(globals, prop, {\n get() {\n return oldvalue;\n },\n set(value) {\n if (oldvalue) {\n globals.removeEventListener(event, oldvalue);\n }\n\n oldvalue = value;\n\n if (oldvalue) {\n globals.addEventListener(event, oldvalue);\n }\n },\n });\n };\n\n // This makes sure that `f` is only run once\n const memoize = (f: () => void) => {\n let run = false;\n\n return () => {\n if (!run) {\n run = true;\n f();\n }\n };\n };\n\n\n // We only start listening for messages / errors when the worker calls addEventListener\n const startOnMessage = memoize(() => {\n $worker.parentPort!.on(\"message\", (data) => {\n workerEvents.dispatchEvent(new MessageEvent(\"message\", { data }));\n });\n });\n\n const startOnMessageError = memoize(() => {\n throw new Error(\"UNIMPLEMENTED\");\n });\n\n const startOnError = memoize(() => {\n $worker.parentPort!.on(\"error\", (data) => {\n workerEvents.dispatchEvent(new Event(\"error\"));\n });\n });\n\n\n // Node workers don't have top-level events, so we have to make our own\n const workerEvents = new EventTarget();\n\n globals.close = () => {\n process.exit();\n };\n\n globals.addEventListener = (type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined) => {\n workerEvents.addEventListener(type, callback, options);\n\n if (type === \"message\") {\n startOnMessage();\n } else if (type === \"messageerror\") {\n startOnMessageError();\n } else if (type === \"error\") {\n startOnError();\n }\n };\n\n globals.removeEventListener = (type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined) => {\n workerEvents.removeEventListener(type, callback, options);\n };\n\n function postMessage(message: any, transfer: Transferable[]): void;\n function postMessage(message: any, options?: StructuredSerializeOptions | undefined): void;\n function postMessage(value: any, transfer: any) {\n $worker.parentPort!.postMessage(value, transfer);\n }\n\n globals.postMessage = postMessage;\n\n makeSetter(\"onmessage\", \"message\");\n makeSetter(\"onmessageerror\", \"messageerror\");\n makeSetter(\"onerror\", \"error\");\n}\n","import \"./polyfill/shared.js\";\nimport \"./polyfill/crypto.js\";\nimport \"./polyfill/fetch.js\";\nimport \"./polyfill/xmlhttprequest.js\";\nimport \"./polyfill/worker.js\";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C;AAC5C,IAAA,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC;AAClC;;ACxLA,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;AACjB,IAAA,UAAkB,CAAC,IAAI,GAAG,UAAU;AACzC"}
1
+ {"version":3,"file":"node-polyfill.js","sources":["../../src/polyfill/crypto.ts","../../src/polyfill/fetch.ts","../../src/polyfill/xmlhttprequest.ts","../../src/polyfill/worker.ts","../../src/node-polyfill.ts"],"sourcesContent":["import { webcrypto } from \"node:crypto\";\n\nif ((globalThis as any).crypto == null) {\n (globalThis as any).crypto = webcrypto;\n}\n","import * as $fs from \"node:fs\";\nimport $mime from \"mime/lite\";\n\n\nconst oldFetch = globalThis.fetch;\n\n\nlet supports: Promise<boolean> | null = null;\n\nasync function checkFetch() {\n try {\n await oldFetch(new URL(\"file:\"));\n return true;\n\n } catch (e) {\n return false;\n }\n}\n\nasync function supportsFetch(): Promise<boolean> {\n if (supports === null) {\n supports = checkFetch();\n }\n\n return await supports;\n}\n\n\n// We always polyfill fetch because Node's fetch doesn't support file URLs.\n(globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise<Response> {\n const request = new Request(resource, options);\n\n const url = new URL(request.url);\n\n if (!(await supportsFetch()) && url.protocol === \"file:\") {\n const readStream = $fs.createReadStream(url);\n\n const headers: HeadersInit = {};\n\n const type = $mime.getType(url.pathname);\n\n if (type) {\n headers[\"Content-Type\"] = type;\n }\n\n return new Response(readStream as any, {\n status: 200,\n statusText: \"OK\",\n headers,\n });\n\n } else {\n return await oldFetch(request);\n }\n};\n","// @ts-ignore\nimport $xmlhttprequest from \"xmlhttprequest-ssl\";\n\nif (globalThis.XMLHttpRequest == null) {\n (globalThis as any).XMLHttpRequest = class extends $xmlhttprequest.XMLHttpRequest {\n constructor(opts?: any) {\n super({ syncPolicy: \"enabled\", ...opts });\n }\n };\n}","import * as $worker from \"node:worker_threads\";\nimport * as $os from \"node:os\";\n\n// This is technically not a part of the Worker polyfill,\n// but Workers are used for multi-threading, so this is often\n// needed when writing Worker code.\nif (globalThis.navigator == null) {\n globalThis.navigator = {\n hardwareConcurrency: $os.cpus().length,\n } as Navigator;\n}\n\nif (globalThis.Worker == null) {\n globalThis.Worker = class Worker extends EventTarget {\n private _worker: import(\"node:worker_threads\").Worker;\n\n constructor(url: string | URL, options?: WorkerOptions | undefined) {\n super();\n\n if (url instanceof URL) {\n if (url.protocol !== \"file:\") {\n throw new Error(\"Worker only supports file: URLs\");\n }\n\n url = url.href;\n\n } else {\n throw new Error(\"Filepaths are unreliable, use `new URL(\\\"...\\\", import.meta.url)` instead.\");\n }\n\n if (!options || options.type !== \"module\") {\n throw new Error(\"Workers must use \\`type: \\\"module\\\"\\`\");\n }\n\n const code = `\n import(\"node:worker_threads\")\n .then(({ workerData }) => {\n return import(workerData.polyfill)\n .then(() => import(workerData.url))\n })\n .catch((e) => {\n // TODO maybe it should send a message to the parent?\n console.error(e.stack);\n });\n `;\n\n this._worker = new $worker.Worker(code, {\n eval: true,\n workerData: {\n url,\n polyfill: new URL(\"node-polyfill.js\", import.meta.url).href,\n },\n });\n\n this._worker.on(\"message\", (data) => {\n this.dispatchEvent(new MessageEvent(\"message\", { data }));\n });\n\n this._worker.on(\"messageerror\", (error) => {\n throw new Error(\"UNIMPLEMENTED\");\n });\n\n this._worker.on(\"error\", (error) => {\n // TODO attach the error to the event somehow\n const event = new Event(\"error\");\n this.dispatchEvent(event);\n });\n }\n\n set onmessage(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n set onmessageerror(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n set onerror(f: () => void) {\n throw new Error(\"UNIMPLEMENTED\");\n }\n\n postMessage(message: any, transfer: Array<Transferable>): void;\n postMessage(message: any, options?: StructuredSerializeOptions | undefined): void;\n postMessage(value: any, transfer: any) {\n this._worker.postMessage(value, transfer);\n }\n\n terminate() {\n this._worker.terminate();\n }\n\n // This is Node-specific, it allows the process to exit\n // even if the Worker is still running.\n unref() {\n this._worker.unref();\n }\n };\n}\n\n\nif (!$worker.isMainThread) {\n const globals = globalThis as unknown as DedicatedWorkerGlobalScope;\n\n // This is used to create the onmessage, onmessageerror, and onerror setters\n const makeSetter = (prop: string, event: string) => {\n let oldvalue: () => void;\n\n Object.defineProperty(globals, prop, {\n get() {\n return oldvalue;\n },\n set(value) {\n if (oldvalue) {\n globals.removeEventListener(event, oldvalue);\n }\n\n oldvalue = value;\n\n if (oldvalue) {\n globals.addEventListener(event, oldvalue);\n }\n },\n });\n };\n\n // This makes sure that `f` is only run once\n const memoize = (f: () => void) => {\n let run = false;\n\n return () => {\n if (!run) {\n run = true;\n f();\n }\n };\n };\n\n\n // We only start listening for messages / errors when the worker calls addEventListener\n const startOnMessage = memoize(() => {\n $worker.parentPort!.on(\"message\", (data) => {\n workerEvents.dispatchEvent(new MessageEvent(\"message\", { data }));\n });\n });\n\n const startOnMessageError = memoize(() => {\n throw new Error(\"UNIMPLEMENTED\");\n });\n\n const startOnError = memoize(() => {\n $worker.parentPort!.on(\"error\", (data) => {\n workerEvents.dispatchEvent(new Event(\"error\"));\n });\n });\n\n\n // Node workers don't have top-level events, so we have to make our own\n const workerEvents = new EventTarget();\n\n globals.close = () => {\n process.exit();\n };\n\n globals.addEventListener = (type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined) => {\n workerEvents.addEventListener(type, callback, options);\n\n if (type === \"message\") {\n startOnMessage();\n } else if (type === \"messageerror\") {\n startOnMessageError();\n } else if (type === \"error\") {\n startOnError();\n }\n };\n\n globals.removeEventListener = (type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined) => {\n workerEvents.removeEventListener(type, callback, options);\n };\n\n function postMessage(message: any, transfer: Transferable[]): void;\n function postMessage(message: any, options?: StructuredSerializeOptions | undefined): void;\n function postMessage(value: any, transfer: any) {\n $worker.parentPort!.postMessage(value, transfer);\n }\n\n globals.postMessage = postMessage;\n\n makeSetter(\"onmessage\", \"message\");\n makeSetter(\"onmessageerror\", \"messageerror\");\n makeSetter(\"onerror\", \"error\");\n}\n","import \"./polyfill/shared.js\";\nimport \"./polyfill/crypto.js\";\nimport \"./polyfill/fetch.js\";\nimport \"./polyfill/xmlhttprequest.js\";\nimport \"./polyfill/worker.js\";\n\nif (!globalThis.self) {\n (globalThis as any).self = globalThis;\n}\n"],"names":[],"mappings":";;;;;;;;AAEA,IAAK,UAAkB,CAAC,MAAM,IAAI,IAAI,EAAE;AACnC,IAAA,UAAkB,CAAC,MAAM,GAAG,SAAS;AAC1C;;ACAA,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK;AAGjC,IAAI,QAAQ,GAA4B,IAAI;AAE5C,eAAe,UAAU,GAAA;AACrB,IAAA,IAAI;QACA,MAAM,QAAQ,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;AAChC,QAAA,OAAO,IAAI;IAEf;IAAE,OAAO,CAAC,EAAE;AACR,QAAA,OAAO,KAAK;IAChB;AACJ;AAEA,eAAe,aAAa,GAAA;AACxB,IAAA,IAAI,QAAQ,KAAK,IAAI,EAAE;QACnB,QAAQ,GAAG,UAAU,EAAE;IAC3B;IAEA,OAAO,MAAM,QAAQ;AACzB;AAGA;AACC,UAAU,CAAC,KAAa,GAAG,gBAAgB,QAA2B,EAAE,OAAgC,EAAA;IACrG,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC;IAE9C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC;AAEhC,IAAA,IAAI,EAAE,MAAM,aAAa,EAAE,CAAC,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,EAAE;QACtD,MAAM,UAAU,GAAG,GAAG,CAAC,gBAAgB,CAAC,GAAG,CAAC;QAE5C,MAAM,OAAO,GAAgB,EAAE;QAE/B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,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O,CAAC,UAAW,CAAC,WAAW,CAAC,KAAK,EAAE,QAAQ,CAAC;IACpD;AAEA,IAAA,OAAO,CAAC,WAAW,GAAG,WAAW;AAEjC,IAAA,UAAU,CAAC,WAAW,EAAE,SAAS,CAAC;AAClC,IAAA,UAAU,CAAC,gBAAgB,EAAE,cAAc,CAAC;AAC5C,IAAA,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC;AAClC;;ACxLA,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;AACjB,IAAA,UAAkB,CAAC,IAAI,GAAG,UAAU;AACzC"}
@@ -1,13 +1,13 @@
1
1
  import './node-polyfill.js';
2
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KEY_STORE, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordScanner, SealanceMerkleTree, VALID_TRANSFER_TYPES, initializeWasm, logAndThrow } from './browser.js';
2
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KEY_STORE, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordScanner, SealanceMerkleTree, VALID_TRANSFER_TYPES, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptViewKey, initializeWasm, isProveApiErrorBody, isProvingResponse, logAndThrow } from './browser.js';
3
3
  export { Address, Authorization, BHP1024, BHP256, BHP512, BHP768, Boolean, Ciphertext, ComputeKey, EncryptionToolkit, ExecutionRequest, ExecutionResponse, Field, Execution as FunctionExecution, GraphKey, Group, I128, I16, I32, I64, I8, OfflineQuery, Pedersen128, Pedersen64, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramManager as ProgramManagerBase, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Scalar, Signature, Transaction, Transition, U128, U16, U32, U64, U8, VerifyingKey, ViewKey, getOrInitConsensusVersionTestHeights, initThreadPool, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
4
4
  import 'core-js/proposals/json-parse-with-source.js';
5
5
  import 'node:crypto';
6
6
  import 'node:fs';
7
7
  import 'mime/lite';
8
8
  import 'xmlhttprequest-ssl';
9
- import 'sync-request';
10
9
  import 'node:worker_threads';
11
10
  import 'node:os';
11
+ import 'libsodium-wrappers';
12
12
  import '@scure/base';
13
13
  //# sourceMappingURL=node.js.map