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