@ar.io/sdk 3.12.0-alpha.1 → 3.12.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/bundles/web.bundle.min.js +170 -167
  2. package/lib/cjs/common/index.js +2 -0
  3. package/lib/cjs/common/wayfinder/gateways/network.js +48 -0
  4. package/lib/cjs/common/wayfinder/gateways/simple-cache.js +35 -0
  5. package/lib/cjs/common/wayfinder/gateways/static.js +13 -0
  6. package/lib/cjs/common/wayfinder/index.js +47 -0
  7. package/lib/cjs/common/wayfinder/routing/strategies/ping.js +72 -0
  8. package/lib/cjs/common/wayfinder/routing/strategies/random.js +13 -0
  9. package/lib/cjs/common/wayfinder/routing/strategies/round-robin.js +42 -0
  10. package/lib/cjs/common/wayfinder/routing/strategies/static.js +29 -0
  11. package/lib/cjs/common/wayfinder/verification/strategies/data-root-verifier.js +139 -0
  12. package/lib/cjs/common/wayfinder/verification/strategies/hash-verifier.js +50 -0
  13. package/lib/cjs/common/wayfinder/verification/trusted.js +106 -0
  14. package/lib/cjs/common/wayfinder/wayfinder.js +735 -0
  15. package/lib/cjs/types/wayfinder.js +3 -0
  16. package/lib/cjs/utils/json.js +0 -1
  17. package/lib/cjs/utils/url.js +3 -1
  18. package/lib/cjs/version.js +1 -1
  19. package/lib/esm/common/index.js +2 -0
  20. package/lib/esm/common/wayfinder/gateways/network.js +44 -0
  21. package/lib/esm/common/wayfinder/gateways/simple-cache.js +31 -0
  22. package/lib/esm/common/wayfinder/gateways/static.js +9 -0
  23. package/lib/esm/common/wayfinder/index.js +31 -0
  24. package/lib/esm/common/wayfinder/routing/strategies/ping.js +68 -0
  25. package/lib/esm/common/wayfinder/routing/strategies/random.js +9 -0
  26. package/lib/esm/common/wayfinder/routing/strategies/round-robin.js +38 -0
  27. package/lib/esm/common/wayfinder/routing/strategies/static.js +25 -0
  28. package/lib/esm/common/wayfinder/verification/strategies/data-root-verifier.js +130 -0
  29. package/lib/esm/common/wayfinder/verification/strategies/hash-verifier.js +46 -0
  30. package/lib/esm/common/wayfinder/verification/trusted.js +102 -0
  31. package/lib/esm/common/wayfinder/wayfinder.js +723 -0
  32. package/lib/esm/types/wayfinder.js +2 -0
  33. package/lib/esm/utils/json.js +0 -1
  34. package/lib/esm/utils/url.js +3 -1
  35. package/lib/esm/version.js +1 -1
  36. package/lib/types/common/index.d.ts +1 -0
  37. package/lib/types/common/wayfinder/gateways/network.d.ts +33 -0
  38. package/lib/types/common/wayfinder/gateways/simple-cache.d.ts +31 -0
  39. package/lib/types/common/wayfinder/gateways/static.d.ts +23 -0
  40. package/lib/types/common/wayfinder/index.d.ts +26 -0
  41. package/lib/types/common/wayfinder/routing/strategies/ping.d.ts +27 -0
  42. package/lib/types/common/wayfinder/routing/strategies/random.d.ts +21 -0
  43. package/lib/types/common/wayfinder/routing/strategies/round-robin.d.ts +29 -0
  44. package/lib/types/common/wayfinder/routing/strategies/static.d.ts +29 -0
  45. package/lib/types/common/wayfinder/verification/strategies/data-root-verifier.d.ts +31 -0
  46. package/lib/types/common/wayfinder/verification/strategies/hash-verifier.d.ts +27 -0
  47. package/lib/types/common/wayfinder/verification/trusted.d.ts +51 -0
  48. package/lib/types/common/wayfinder/wayfinder.d.ts +299 -0
  49. package/lib/types/types/wayfinder.d.ts +66 -0
  50. package/lib/types/utils/json.d.ts +1 -1
  51. package/lib/types/version.d.ts +1 -1
  52. package/package.json +3 -2
  53. package/lib/cjs/types/ant.test.js +0 -150
  54. package/lib/cjs/types/token.test.js +0 -83
  55. package/lib/cjs/utils/ant.test.js +0 -111
  56. package/lib/cjs/utils/b64.test.js +0 -72
  57. package/lib/cjs/utils/url.test.js +0 -24
  58. package/lib/cjs/utils/utils.test.js +0 -194
  59. package/lib/esm/types/ant.test.js +0 -148
  60. package/lib/esm/types/token.test.js +0 -81
  61. package/lib/esm/utils/ant.test.js +0 -109
  62. package/lib/esm/utils/b64.test.js +0 -70
  63. package/lib/esm/utils/url.test.js +0 -19
  64. package/lib/esm/utils/utils.test.js +0 -192
  65. package/lib/types/types/ant.test.d.ts +0 -1
  66. package/lib/types/types/token.test.d.ts +0 -1
  67. package/lib/types/utils/ant.test.d.ts +0 -1
  68. package/lib/types/utils/b64.test.d.ts +0 -1
  69. package/lib/types/utils/url.test.d.ts +0 -1
  70. package/lib/types/utils/utils.test.d.ts +0 -1
@@ -0,0 +1,735 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Wayfinder = exports.createWayfinderClient = exports.WayfinderEmitter = exports.resolveWayfinderUrl = exports.txIdRegex = exports.arnsRegex = void 0;
7
+ exports.tapAndVerifyStream = tapAndVerifyStream;
8
+ exports.wrapVerifiedResponse = wrapVerifiedResponse;
9
+ /**
10
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
11
+ *
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * you may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ *
16
+ * http://www.apache.org/licenses/LICENSE-2.0
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ */
24
+ const node_events_1 = __importDefault(require("node:events"));
25
+ const node_stream_1 = require("node:stream");
26
+ const io_js_1 = require("../io.js");
27
+ const logger_js_1 = require("../logger.js");
28
+ const network_js_1 = require("./gateways/network.js");
29
+ const simple_cache_js_1 = require("./gateways/simple-cache.js");
30
+ const static_js_1 = require("./gateways/static.js");
31
+ const ping_js_1 = require("./routing/strategies/ping.js");
32
+ const hash_verifier_js_1 = require("./verification/strategies/hash-verifier.js");
33
+ const trusted_js_1 = require("./verification/trusted.js");
34
+ // known regexes for wayfinder urls
35
+ exports.arnsRegex = /^[a-z0-9_-]{1,51}$/;
36
+ exports.txIdRegex = /^[A-Za-z0-9_-]{43}$/;
37
+ /**
38
+ * Core function that converts a wayfinder url to the proper ar-io gateway URL
39
+ * @param originalUrl - the wayfinder url to resolve
40
+ * @param selectedGateway - the target gateway to resolve the url against
41
+ * @returns the resolved url that can be used to make a request
42
+ */
43
+ const resolveWayfinderUrl = ({ originalUrl, selectedGateway, logger, }) => {
44
+ if (originalUrl.toString().startsWith('ar://')) {
45
+ logger?.debug(`Applying wayfinder routing protocol to ${originalUrl}`, {
46
+ originalUrl,
47
+ });
48
+ const [, path] = originalUrl.toString().split('ar://');
49
+ // e.g. ar:///info should route to the info endpoint of the target gateway
50
+ if (path.startsWith('/')) {
51
+ logger?.debug(`Routing to ${path.slice(1)} on ${selectedGateway}`, {
52
+ originalUrl,
53
+ selectedGateway,
54
+ });
55
+ return new URL(path.slice(1), selectedGateway);
56
+ }
57
+ // TODO: this breaks 43 character named arns names - we should check a a local name cache list before resolving raw transaction ids
58
+ if (exports.txIdRegex.test(path)) {
59
+ const [txId, ...rest] = path.split('/');
60
+ return new URL(`${txId}${rest.join('/')}`, selectedGateway);
61
+ }
62
+ if (exports.arnsRegex.test(path)) {
63
+ // TODO: tests to ensure arns names support query params and paths
64
+ const [name, ...rest] = path.split('/');
65
+ const arnsUrl = `${selectedGateway.protocol}//${name}.${selectedGateway.hostname}${selectedGateway.port ? `:${selectedGateway.port}` : ''}`;
66
+ logger?.debug(`Routing to ${path} on ${arnsUrl}`, {
67
+ originalUrl,
68
+ selectedGateway,
69
+ });
70
+ return new URL(rest.join('/'), arnsUrl);
71
+ }
72
+ // TODO: support .eth addresses
73
+ // TODO: "gasless" routing via DNS TXT records (e.g. ar://gatewaypie.com -> TXT record lookup for TX ID and redirect to that gateway)
74
+ }
75
+ logger?.debug('No wayfinder routing protocol applied', {
76
+ originalUrl,
77
+ });
78
+ // return the original url if it's not a wayfinder url (allows you to use the wayfinder client with non-wayfinder urls)
79
+ return new URL(originalUrl);
80
+ };
81
+ exports.resolveWayfinderUrl = resolveWayfinderUrl;
82
+ class WayfinderEmitter extends node_events_1.default {
83
+ constructor({ onVerificationPassed, onVerificationFailed, onVerificationProgress,
84
+ // TODO: continue this pattern for all events
85
+ } = {}) {
86
+ super();
87
+ if (onVerificationPassed) {
88
+ this.on('verification-succeeded', onVerificationPassed);
89
+ }
90
+ if (onVerificationFailed) {
91
+ this.on('verification-failed', onVerificationFailed);
92
+ }
93
+ if (onVerificationProgress) {
94
+ this.on('verification-progress', onVerificationProgress);
95
+ }
96
+ }
97
+ emit(event, payload) {
98
+ return super.emit(event, payload);
99
+ }
100
+ on(event, listener) {
101
+ return super.on(event, listener);
102
+ }
103
+ }
104
+ exports.WayfinderEmitter = WayfinderEmitter;
105
+ function tapAndVerifyStream({ originalStream, contentLength, verifyData, txId, emitter, strict = false, }) {
106
+ // taps node streams
107
+ if (originalStream instanceof node_stream_1.Readable &&
108
+ typeof originalStream.pipe === 'function') {
109
+ const tappedClientStream = new node_stream_1.PassThrough();
110
+ const streamToVerify = new node_stream_1.PassThrough();
111
+ // kick off the verification promise, this will be awaited when the original stream ends
112
+ const verificationPromise = verifyData({
113
+ data: streamToVerify,
114
+ txId,
115
+ });
116
+ let bytesProcessed = 0;
117
+ // pipe the original stream to the verifier and the client stream
118
+ originalStream.on('data', (chunk) => {
119
+ streamToVerify.write(chunk);
120
+ tappedClientStream.write(chunk);
121
+ bytesProcessed += chunk.length;
122
+ // only emit if contentLength is not 0
123
+ if (contentLength !== 0) {
124
+ emitter?.emit('verification-progress', {
125
+ txId,
126
+ totalBytes: contentLength,
127
+ processedBytes: bytesProcessed,
128
+ });
129
+ }
130
+ });
131
+ originalStream.on('end', async () => {
132
+ streamToVerify.end(); // triggers verifier completion and completes the verification promise
133
+ if (strict) {
134
+ // in strict mode, we wait for verification to complete before ending the client stream
135
+ try {
136
+ await verificationPromise;
137
+ emitter?.emit('verification-succeeded', { txId });
138
+ tappedClientStream.end();
139
+ }
140
+ catch (error) {
141
+ emitter?.emit('verification-failed', { error, txId });
142
+ // In strict mode, destroy the client stream with the error
143
+ tappedClientStream.destroy(new Error('Verification failed', { cause: error }));
144
+ }
145
+ }
146
+ else {
147
+ // in non-strict mode, we end the client stream immediately and handle verification asynchronously
148
+ tappedClientStream.end();
149
+ // trigger the verification promise and emit events for the result
150
+ verificationPromise
151
+ .then(() => {
152
+ emitter?.emit('verification-succeeded', { txId });
153
+ })
154
+ .catch((error) => {
155
+ emitter?.emit('verification-failed', { error, txId });
156
+ });
157
+ }
158
+ });
159
+ originalStream.on('error', (err) => {
160
+ // emit the verification failed event
161
+ emitter?.emit('verification-failed', {
162
+ error: err,
163
+ txId,
164
+ });
165
+ // destroy both streams and propagate the original stream error
166
+ streamToVerify.destroy(err);
167
+ tappedClientStream.destroy(err);
168
+ });
169
+ // send the stream to the verify function and if it errors end the client stream
170
+ return tappedClientStream;
171
+ }
172
+ // taps web readable streams
173
+ if (originalStream instanceof ReadableStream &&
174
+ typeof originalStream.tee === 'function') {
175
+ const [verifyBranch, clientBranch] = originalStream.tee();
176
+ // setup our promise to verify the data
177
+ const verificationPromise = verifyData({
178
+ data: verifyBranch,
179
+ txId,
180
+ });
181
+ let bytesProcessed = 0;
182
+ const reader = clientBranch.getReader();
183
+ const clientStreamWithVerification = new ReadableStream({
184
+ async pull(controller) {
185
+ const { done, value } = await reader.read();
186
+ if (done) {
187
+ if (strict) {
188
+ // in strict mode, we wait for verification to complete before closing the controller
189
+ try {
190
+ await verificationPromise;
191
+ emitter?.emit('verification-succeeded', { txId });
192
+ controller.close();
193
+ }
194
+ catch (err) {
195
+ emitter?.emit('verification-failed', {
196
+ txId,
197
+ error: err,
198
+ });
199
+ // In strict mode, we report the error to the client stream
200
+ controller.error(new Error('Verification failed', { cause: err }));
201
+ }
202
+ }
203
+ else {
204
+ // trigger the verification promise and emit events for the result
205
+ verificationPromise
206
+ .then(() => {
207
+ emitter?.emit('verification-succeeded', { txId });
208
+ })
209
+ .catch((error) => {
210
+ emitter?.emit('verification-failed', {
211
+ txId,
212
+ error,
213
+ });
214
+ });
215
+ // in non-strict mode, we close the controller immediately and handle verification asynchronously
216
+ controller.close();
217
+ }
218
+ }
219
+ else {
220
+ bytesProcessed += value.length;
221
+ emitter?.emit('verification-progress', {
222
+ txId,
223
+ totalBytes: contentLength,
224
+ processedBytes: bytesProcessed,
225
+ });
226
+ controller.enqueue(value);
227
+ }
228
+ },
229
+ cancel(reason) {
230
+ // cancel the reader regardless of verification status
231
+ reader.cancel(reason);
232
+ // emit the verification cancellation event
233
+ emitter?.emit('verification-failed', {
234
+ txId,
235
+ error: new Error('Verification cancelled', {
236
+ cause: {
237
+ reason,
238
+ },
239
+ }),
240
+ });
241
+ // note: we don't block or throw errors here even in strict mode
242
+ // since the stream is already being cancelled by the client
243
+ },
244
+ });
245
+ return clientStreamWithVerification;
246
+ }
247
+ throw new Error('Unsupported body type for cloning');
248
+ }
249
+ function wrapVerifiedResponse(original, newBody, txId) {
250
+ // Clone headers (Header objects aren't serializable)
251
+ const headers = new Headers();
252
+ original.headers.forEach((value, key) => headers.set(key, value));
253
+ // Create a new Response with the new body and cloned headers
254
+ const wrapped = new Response(newBody, {
255
+ status: original.status,
256
+ statusText: original.statusText,
257
+ headers,
258
+ });
259
+ // Attach txId for downstream tracking
260
+ wrapped.txId = txId;
261
+ wrapped.redirectedFrom = original.url;
262
+ return wrapped;
263
+ }
264
+ /**
265
+ * Creates a wrapped http client that supports ar:// protocol
266
+ *
267
+ * This function leverages a Proxy to intercept calls to the http client
268
+ * and redirects them to the target gateway using the resolveUrl function url.
269
+ * It also supports the http client methods like get(), post(), put(), delete(), etc.
270
+ *
271
+ * Any URLs provided that are not wayfinder urls will be returned as is.
272
+ *
273
+ * @param httpClient - the http client to wrap (e.g. axios, fetch, got, etc.)
274
+ * @param resolveUrl - the function to construct the redirect url for ar:// requests
275
+ * @returns a wrapped http client that supports ar:// protocol
276
+ */
277
+ const createWayfinderClient = ({ httpClient, resolveUrl, verifyData, selectGateway, emitter = new WayfinderEmitter(), logger, strict = false, }) => {
278
+ const wayfinderRedirect = async (fn, rawArgs) => {
279
+ // TODO: handle if first arg is not a string (i.e. just return the result of the function call)
280
+ const [originalUrl, ...rest] = rawArgs;
281
+ if (typeof originalUrl !== 'string') {
282
+ logger?.debug('Original URL is not a string, skipping routing', {
283
+ originalUrl,
284
+ });
285
+ emitter?.emit('routing-skipped', {
286
+ originalUrl: JSON.stringify(originalUrl),
287
+ });
288
+ return fn(...rawArgs);
289
+ }
290
+ emitter?.emit('routing-started', {
291
+ originalUrl: originalUrl.toString(),
292
+ });
293
+ // TODO: by default we will retry 3 times but this should be configurable and moved to a routing strategy
294
+ const maxRetries = 3;
295
+ const retryDelay = 1000;
296
+ for (let i = 0; i < maxRetries; i++) {
297
+ try {
298
+ // select the target gateway
299
+ const selectedGateway = await selectGateway();
300
+ logger?.debug('Selected gateway', {
301
+ originalUrl,
302
+ selectedGateway: selectedGateway.toString(),
303
+ });
304
+ // route the request to the target gateway
305
+ const redirectUrl = resolveUrl({
306
+ originalUrl,
307
+ selectedGateway,
308
+ logger,
309
+ });
310
+ emitter?.emit('routing-succeeded', {
311
+ originalUrl,
312
+ selectedGateway: selectedGateway.toString(),
313
+ redirectUrl: redirectUrl.toString(),
314
+ });
315
+ logger?.debug(`Redirecting request`, {
316
+ originalUrl,
317
+ redirectUrl: redirectUrl.toString(),
318
+ });
319
+ // make the request to the target gateway using the redirect url and http client
320
+ const response = await fn(redirectUrl.toString(), ...rest);
321
+ // TODO: trigger a routing event with the raw response object?
322
+ logger?.debug(`Successfully routed request to gateway`, {
323
+ redirectUrl: redirectUrl.toString(),
324
+ originalUrl: originalUrl.toString(),
325
+ });
326
+ // only verify data if the redirect url is different from the original url
327
+ if (response && redirectUrl.toString() !== originalUrl.toString()) {
328
+ if (verifyData) {
329
+ // if the headers do not have .get on them, we need to parse the headers manually
330
+ const headers = new Headers();
331
+ const headersObject = response.headers ?? {};
332
+ if (headersObject instanceof Map) {
333
+ for (const [key, value] of headersObject.entries()) {
334
+ headers.set(key, value);
335
+ }
336
+ }
337
+ else if (headersObject instanceof Headers) {
338
+ for (const [key, value] of headersObject.entries()) {
339
+ headers.set(key, value);
340
+ }
341
+ }
342
+ else if (headersObject !== undefined &&
343
+ typeof headersObject === 'object') {
344
+ for (const [key, value] of Object.entries(headersObject)) {
345
+ headers.set(key, value);
346
+ }
347
+ }
348
+ else {
349
+ throw new Error('Gateway did not return headers needed for verification', {
350
+ cause: {
351
+ redirectUrl: redirectUrl.toString(),
352
+ originalUrl: originalUrl.toString(),
353
+ },
354
+ });
355
+ }
356
+ // transaction id is either in the response headers or the path of the request as the first parameter
357
+ // TODO: we may want to move this parsing to be returned by the resolveUrl function depending on the redirect URL we've constructed
358
+ const txId = headers.get('x-arns-resolved-id') ??
359
+ redirectUrl.pathname.split('/')[1];
360
+ // TODO: validate nodes return content length for all responses
361
+ const contentLength = +(headers.get('content-length') ?? 0);
362
+ if (!exports.txIdRegex.test(txId)) {
363
+ // no transaction id found, skip verification
364
+ logger?.debug('No transaction id found, skipping verification', {
365
+ redirectUrl: redirectUrl.toString(),
366
+ originalUrl,
367
+ });
368
+ emitter?.emit('verification-skipped', {
369
+ originalUrl,
370
+ });
371
+ return response;
372
+ }
373
+ emitter?.emit('identified-transaction-id', {
374
+ originalUrl,
375
+ selectedGateway: redirectUrl.toString(),
376
+ txId,
377
+ });
378
+ // parse out the key that contains the response body, we'll use it later when updating the response object
379
+ const responseDataKey = response.body
380
+ ? 'body'
381
+ : response.data
382
+ ? 'data'
383
+ : undefined;
384
+ if (responseDataKey === undefined) {
385
+ throw new Error('No data body or data provided, skipping verification', {
386
+ cause: {
387
+ redirectUrl: redirectUrl.toString(),
388
+ originalUrl: originalUrl.toString(),
389
+ },
390
+ });
391
+ }
392
+ const responseBody = response[responseDataKey];
393
+ // TODO: determine if it is data item or L1 transaction, and tell the verifier accordingly, just drop in hit to graphql now
394
+ if (txId === undefined) {
395
+ throw new Error('Failed to parse data hash from response headers', {
396
+ cause: {
397
+ redirectUrl: redirectUrl.toString(),
398
+ originalUrl: originalUrl.toString(),
399
+ txId,
400
+ },
401
+ });
402
+ }
403
+ else if (responseBody === undefined) {
404
+ throw new Error('No data body provided, skipping verification', {
405
+ cause: {
406
+ redirectUrl: redirectUrl.toString(),
407
+ originalUrl: originalUrl.toString(),
408
+ txId,
409
+ },
410
+ });
411
+ }
412
+ else {
413
+ logger?.debug('Verifying data hash for txId', {
414
+ redirectUrl: redirectUrl.toString(),
415
+ originalUrl: originalUrl.toString(),
416
+ txId,
417
+ });
418
+ if (responseBody instanceof ReadableStream ||
419
+ responseBody instanceof node_stream_1.Readable) {
420
+ const newClientStream = tapAndVerifyStream({
421
+ originalStream: responseBody,
422
+ contentLength,
423
+ verifyData,
424
+ txId,
425
+ emitter,
426
+ strict,
427
+ });
428
+ if (response instanceof Response) {
429
+ // specific to fetch
430
+ return wrapVerifiedResponse(response, newClientStream, txId);
431
+ }
432
+ else {
433
+ // overwrite the response body with the new client stream
434
+ response.txId = txId;
435
+ response.body = newClientStream;
436
+ return response;
437
+ }
438
+ }
439
+ else {
440
+ // TODO: content-application/json and it's smaller than 10mb
441
+ // TODO: add tests and verify this works for all non-Readable/streamed responses
442
+ if (strict) {
443
+ // In strict mode, wait for verification before returning response
444
+ try {
445
+ await verifyData({
446
+ data: responseBody,
447
+ txId,
448
+ });
449
+ emitter?.emit('verification-succeeded', { txId });
450
+ return response;
451
+ }
452
+ catch (error) {
453
+ logger?.debug('Failed to verify data hash', {
454
+ error,
455
+ txId,
456
+ });
457
+ emitter?.emit('verification-failed', { txId, error });
458
+ throw new Error('Verification failed', { cause: error });
459
+ }
460
+ }
461
+ else {
462
+ // In non-strict mode, perform verification in the background
463
+ verifyData({
464
+ data: responseBody,
465
+ txId,
466
+ })
467
+ .then(() => {
468
+ emitter?.emit('verification-succeeded', { txId });
469
+ })
470
+ .catch((error) => {
471
+ logger?.debug('Failed to verify data hash', {
472
+ error,
473
+ txId,
474
+ });
475
+ emitter?.emit('verification-failed', { txId, error });
476
+ });
477
+ return response;
478
+ }
479
+ }
480
+ }
481
+ }
482
+ }
483
+ // TODO: if strict - wait for verification to finish and succeed before returning the response
484
+ return response;
485
+ }
486
+ catch (error) {
487
+ logger?.debug('Failed to route request', {
488
+ error: error.message,
489
+ stack: error.stack,
490
+ originalUrl,
491
+ attempt: i + 1,
492
+ maxRetries,
493
+ });
494
+ if (i < maxRetries - 1) {
495
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
496
+ }
497
+ }
498
+ }
499
+ throw new Error('Failed to route request after max retries', {
500
+ cause: {
501
+ originalUrl,
502
+ maxRetries,
503
+ },
504
+ });
505
+ };
506
+ return new Proxy(httpClient, {
507
+ // support direct calls: fetch('ar://…', options)
508
+ // axios() or got()
509
+ apply: (_target, _thisArg, argArray) => wayfinderRedirect(httpClient, argArray),
510
+ // support http clients that use functions like `got.get`, `got.post`, `axios.get`, etc. while still using the wayfinder redirect function
511
+ get: (target, prop, receiver) => {
512
+ const value = Reflect.get(target, prop, receiver);
513
+ if (typeof value === 'function') {
514
+ return (...inner) => wayfinderRedirect(value.bind(target), inner);
515
+ }
516
+ return value; // numbers, objects, symbols pass through untouched
517
+ },
518
+ });
519
+ };
520
+ exports.createWayfinderClient = createWayfinderClient;
521
+ /**
522
+ * The main class for the wayfinder
523
+ * @param router - the router to use for requests
524
+ * @param httpClient - the http client to use for requests
525
+ * @param blocklist - the blocklist of gateways to avoid
526
+ */
527
+ class Wayfinder {
528
+ /**
529
+ * The native http client used by wayfinder. By default, the native fetch api is used.
530
+ *
531
+ * @example
532
+ * const wayfinder = new Wayfinder({
533
+ * httpClient: axios,
534
+ * });
535
+ *
536
+ */
537
+ httpClient;
538
+ /**
539
+ * The gateways provider is responsible for providing the list of gateways to use for routing requests.
540
+ *
541
+ * @example
542
+ * const wayfinder = new Wayfinder({
543
+ * gatewaysProvider: new SimpleCacheGatewaysProvider({
544
+ * gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
545
+ * ttlSeconds: 60 * 60 * 24, // 1 day
546
+ * }),
547
+ * });
548
+ */
549
+ gatewaysProvider;
550
+ /**
551
+ * The routing strategy to use when routing requests.
552
+ *
553
+ * @example
554
+ * const wayfinder = new Wayfinder({
555
+ * strategy: new FastestPingStrategy({
556
+ * timeoutMs: 1000,
557
+ * }),
558
+ * });
559
+ */
560
+ routingStrategy;
561
+ /**
562
+ * A helper function that resolves the redirect url for ar:// requests to a target gateway.
563
+ *
564
+ * Note: no verification is done when resolving an ar://<path> url to a wayfinder route.
565
+ * In order to verify the data, you must use the `request` function or request the data and
566
+ * verify it yourself via the `verifyData` function.
567
+ *
568
+ * @example
569
+ * const { resolveUrl } = new Wayfinder();
570
+ *
571
+ * // returns the redirected URL based on the routing strategy and the original url
572
+ * const redirectUrl = await resolveUrl({ originalUrl: 'ar://example' });
573
+ *
574
+ * window.open(redirectUrl.toString(), '_blank');
575
+ */
576
+ resolveUrl;
577
+ /**
578
+ *
579
+ * A wrapped http client that supports ar:// protocol. If a verification strategy is provided,
580
+ * the request will be verified and events will be emitted as the request is processed.
581
+ *
582
+ * @example
583
+ * const wayfinder = new Wayfinder({
584
+ * verificationStrategy: new HashVerificationStrategy({
585
+ * trustedHashProvider: new TrustedGatewaysHashProvider({
586
+ * gatewaysProvider: new StaticGatewaysProvider({
587
+ * gateways: ['https://permagate.io'],
588
+ * }),
589
+ * }),
590
+ * }),
591
+ * })
592
+ *
593
+ * // request an arns name
594
+ * const response = await wayfinder.request('ar://ardrive')
595
+ *
596
+ * // request a transaction id
597
+ * const response = await wayfinder.request('ar://1234567890')
598
+ *
599
+ * // request a transaction id with a custom http client
600
+ * const response = await wayfinder.request('ar://1234567890')
601
+ *
602
+ * // Set strict mode to true to make verification blocking
603
+ * const wayfinder = new Wayfinder({
604
+ * strict: true,
605
+ * });
606
+ *
607
+ * // This will throw an error if verification fails
608
+ * try {
609
+ * const response = await wayfinder.request('ar://1234567890');
610
+ * } catch (error) {
611
+ * console.error('Verification failed', error);
612
+ * }
613
+ */
614
+ request;
615
+ /**
616
+ * The function that verifies the data hash for a given transaction id.
617
+ *
618
+ * @example
619
+ * const wayfinder = new Wayfinder({
620
+ * verifyData: (data, txId) => {
621
+ * // some custom verification logic
622
+ * return true;
623
+ * },
624
+ * });
625
+ */
626
+ verifyData;
627
+ /**
628
+ * Whether verification should be strict (blocking) or not.
629
+ * If true, verification failures will cause requests to fail.
630
+ * If false, verification will be performed asynchronously and failures will only emit events.
631
+ */
632
+ strict;
633
+ /**
634
+ * The event emitter for wayfinder that emits verification events.
635
+ *
636
+ * const wayfinder = new Wayfinder()
637
+ *
638
+ * wayfinder.emitter.on('verification-succeeded', (event) => {
639
+ * console.log('Verification passed!', event);
640
+ * })
641
+ *
642
+ * wayfinder.emitter.on('verification-failed', (event) => {
643
+ * console.log('Verification failed!', event);
644
+ * })
645
+ *
646
+ * or implement the events interface and pass it in, using callback functions
647
+ *
648
+ * const wayfinder = new Wayfinder({
649
+ * events: {
650
+ * onVerificationPassed: (event) => {
651
+ * console.log('Verification passed!', event);
652
+ * },
653
+ * onVerificationFailed: (event) => {
654
+ * console.log('Verification failed!', event);
655
+ * },
656
+ * onVerificationProgress: (event) => {
657
+ * console.log('Verification progress!', event);
658
+ * },
659
+ * }
660
+ * })
661
+ *
662
+ * const response = await wayfind('ar://example');
663
+ */
664
+ emitter;
665
+ /**
666
+ * The constructor for the wayfinder
667
+ * @param httpClient - the http client to use for requests
668
+ * @param routingStrategy - the routing strategy to use for requests
669
+ * @param verificationStrategy - the verification strategy to use for requests
670
+ * @param gatewaysProvider - the gateways provider to use for routing requests
671
+ * @param logger - the logger to use for logging
672
+ * @param strict - if true, verification will be blocking and will fail requests if verification fails; if false, verification will be non-blocking
673
+ */
674
+ constructor({ httpClient = fetch, logger = logger_js_1.Logger.default, gatewaysProvider = new simple_cache_js_1.SimpleCacheGatewaysProvider({
675
+ gatewaysProvider: new network_js_1.NetworkGatewaysProvider({
676
+ ario: io_js_1.ARIO.mainnet(),
677
+ }),
678
+ ttlSeconds: 60 * 60, // 1 hour
679
+ }), routingStrategy = new ping_js_1.FastestPingRoutingStrategy({
680
+ timeoutMs: 1000,
681
+ }), verificationStrategy = new hash_verifier_js_1.HashVerificationStrategy({
682
+ trustedHashProvider: new trusted_js_1.TrustedGatewaysHashProvider({
683
+ gatewaysProvider: new static_js_1.StaticGatewaysProvider({
684
+ gateways: ['https://permagate.io'],
685
+ }),
686
+ }),
687
+ }), events = {
688
+ onVerificationPassed: (event) => {
689
+ logger.debug('Verification passed!', event);
690
+ },
691
+ onVerificationFailed: (event) => {
692
+ logger.error('Verification failed!', event);
693
+ },
694
+ onVerificationProgress: (event) => {
695
+ logger.debug('Verification progress!', event);
696
+ },
697
+ }, strict = false,
698
+ // TODO: stats provider
699
+ }) {
700
+ this.routingStrategy = routingStrategy;
701
+ this.gatewaysProvider = gatewaysProvider;
702
+ this.httpClient = httpClient;
703
+ this.emitter = new WayfinderEmitter(events);
704
+ this.verifyData =
705
+ verificationStrategy.verifyData.bind(verificationStrategy);
706
+ this.strict = strict;
707
+ // top level function to easily resolve wayfinder urls using the routing strategy and gateways provider
708
+ this.resolveUrl = async ({ originalUrl, logger }) => {
709
+ const selectedGateway = await this.routingStrategy.selectGateway({
710
+ gateways: await this.gatewaysProvider.getGateways(),
711
+ });
712
+ return (0, exports.resolveWayfinderUrl)({
713
+ originalUrl,
714
+ selectedGateway,
715
+ logger,
716
+ });
717
+ };
718
+ // create a wayfinder client with the routing strategy and gateways provider
719
+ this.request = (0, exports.createWayfinderClient)({
720
+ httpClient,
721
+ selectGateway: async () => {
722
+ return this.routingStrategy.selectGateway({
723
+ gateways: await this.gatewaysProvider.getGateways(),
724
+ });
725
+ },
726
+ resolveUrl: exports.resolveWayfinderUrl,
727
+ verifyData: this.verifyData,
728
+ emitter: this.emitter,
729
+ logger,
730
+ strict,
731
+ });
732
+ logger?.debug(`Wayfinder initialized with ${routingStrategy.constructor.name} routing strategy`);
733
+ }
734
+ }
735
+ exports.Wayfinder = Wayfinder;