@ar.io/sdk 3.10.0 → 3.11.0-alpha.2

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 (99) hide show
  1. package/README.md +66 -125
  2. package/bundles/web.bundle.min.js +130 -125
  3. package/lib/cjs/cli/options.js +12 -0
  4. package/lib/cjs/cli/utils.js +32 -10
  5. package/lib/cjs/cli/wayfinder.js +34 -0
  6. package/lib/cjs/common/ant-versions.js +5 -5
  7. package/lib/cjs/common/index.js +2 -0
  8. package/lib/cjs/common/io.js +64 -1
  9. package/lib/cjs/common/turbo.js +208 -0
  10. package/lib/cjs/common/wayfinder/gateways.js +75 -0
  11. package/lib/cjs/common/wayfinder/index.js +38 -0
  12. package/lib/cjs/common/wayfinder/routers/fixed.js +14 -0
  13. package/lib/cjs/common/wayfinder/routers/fixed.test.js +14 -0
  14. package/lib/cjs/common/wayfinder/routers/priority.js +38 -0
  15. package/lib/cjs/common/wayfinder/routers/priority.test.js +155 -0
  16. package/lib/cjs/common/wayfinder/routers/random.js +23 -0
  17. package/lib/cjs/common/wayfinder/routers/random.test.js +104 -0
  18. package/lib/cjs/common/wayfinder/routers/simple-cache.js +25 -0
  19. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +41 -0
  20. package/lib/cjs/common/wayfinder/wayfinder.js +174 -0
  21. package/lib/cjs/common/wayfinder/wayfinder.test.js +253 -0
  22. package/lib/cjs/types/ant.js +12 -1
  23. package/lib/cjs/types/index.js +1 -0
  24. package/lib/cjs/types/io.js +1 -1
  25. package/lib/cjs/types/wayfinder.js +2 -0
  26. package/lib/cjs/utils/ao.js +5 -0
  27. package/lib/cjs/utils/random.js +30 -0
  28. package/lib/cjs/utils/url.js +28 -0
  29. package/lib/cjs/utils/url.test.js +24 -0
  30. package/lib/cjs/utils/utils.test.js +8 -8
  31. package/lib/cjs/version.js +1 -1
  32. package/lib/cjs/web/index.js +3 -1
  33. package/lib/esm/cli/options.js +12 -0
  34. package/lib/esm/cli/utils.js +31 -10
  35. package/lib/esm/cli/wayfinder.js +32 -0
  36. package/lib/esm/common/ant-versions.js +5 -5
  37. package/lib/esm/common/index.js +2 -0
  38. package/lib/esm/common/io.js +64 -1
  39. package/lib/esm/common/turbo.js +200 -0
  40. package/lib/esm/common/wayfinder/gateways.js +69 -0
  41. package/lib/esm/common/wayfinder/index.js +22 -0
  42. package/lib/esm/common/wayfinder/routers/fixed.js +10 -0
  43. package/lib/esm/common/wayfinder/routers/fixed.test.js +12 -0
  44. package/lib/esm/common/wayfinder/routers/priority.js +34 -0
  45. package/lib/esm/common/wayfinder/routers/priority.test.js +153 -0
  46. package/lib/esm/common/wayfinder/routers/random.js +19 -0
  47. package/lib/esm/common/wayfinder/routers/random.test.js +102 -0
  48. package/lib/esm/common/wayfinder/routers/simple-cache.js +21 -0
  49. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +39 -0
  50. package/lib/esm/common/wayfinder/wayfinder.js +168 -0
  51. package/lib/esm/common/wayfinder/wayfinder.test.js +248 -0
  52. package/lib/esm/types/ant.js +11 -0
  53. package/lib/esm/types/index.js +1 -0
  54. package/lib/esm/types/io.js +1 -1
  55. package/lib/esm/types/wayfinder.js +1 -0
  56. package/lib/esm/utils/ao.js +5 -0
  57. package/lib/esm/utils/random.js +26 -0
  58. package/lib/esm/utils/url.js +24 -0
  59. package/lib/esm/utils/url.test.js +19 -0
  60. package/lib/esm/utils/utils.test.js +1 -1
  61. package/lib/esm/version.js +1 -1
  62. package/lib/esm/web/index.js +1 -1
  63. package/lib/types/cli/commands/antCommands.d.ts +3 -3
  64. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +1 -1
  65. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +9 -9
  66. package/lib/types/cli/commands/readCommands.d.ts +1 -0
  67. package/lib/types/cli/commands/transfer.d.ts +3 -3
  68. package/lib/types/cli/options.d.ts +9 -0
  69. package/lib/types/cli/types.d.ts +3 -0
  70. package/lib/types/cli/utils.d.ts +4 -0
  71. package/lib/types/cli/wayfinder.d.ts +1 -0
  72. package/lib/types/common/ant-versions.d.ts +3 -6
  73. package/lib/types/common/index.d.ts +1 -0
  74. package/lib/types/common/io.d.ts +9 -7
  75. package/lib/types/common/turbo.d.ts +62 -0
  76. package/lib/types/common/wayfinder/gateways.d.ts +44 -0
  77. package/lib/types/common/wayfinder/index.d.ts +20 -0
  78. package/lib/types/common/wayfinder/routers/fixed.d.ts +24 -0
  79. package/lib/types/common/wayfinder/routers/fixed.test.d.ts +1 -0
  80. package/lib/types/common/wayfinder/routers/priority.d.ts +33 -0
  81. package/lib/types/common/wayfinder/routers/priority.test.d.ts +1 -0
  82. package/lib/types/common/wayfinder/routers/random.d.ts +27 -0
  83. package/lib/types/common/wayfinder/routers/random.test.d.ts +1 -0
  84. package/lib/types/common/wayfinder/routers/simple-cache.d.ts +28 -0
  85. package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +1 -0
  86. package/lib/types/common/wayfinder/wayfinder.d.ts +120 -0
  87. package/lib/types/common/wayfinder/wayfinder.test.d.ts +1 -0
  88. package/lib/types/types/ant.d.ts +53 -1
  89. package/lib/types/types/common.d.ts +7 -2
  90. package/lib/types/types/index.d.ts +1 -0
  91. package/lib/types/types/io.d.ts +7 -5
  92. package/lib/types/types/wayfinder.d.ts +19 -0
  93. package/lib/types/utils/ao.d.ts +1 -12
  94. package/lib/types/utils/random.d.ts +7 -0
  95. package/lib/types/utils/url.d.ts +19 -0
  96. package/lib/types/utils/url.test.d.ts +1 -0
  97. package/lib/types/version.d.ts +1 -1
  98. package/lib/types/web/index.d.ts +1 -1
  99. package/package.json +5 -3
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_assert_1 = require("node:assert");
4
+ const node_test_1 = require("node:test");
5
+ const fixed_js_1 = require("./fixed.js");
6
+ (0, node_test_1.describe)('FixedRouter', () => {
7
+ (0, node_test_1.it)('should return the provided gateway', async () => {
8
+ const router = new fixed_js_1.FixedGatewayRouter({
9
+ gateway: new URL('http://test-gateway.net'),
10
+ });
11
+ const result = await router.getTargetGateway();
12
+ node_assert_1.strict.deepStrictEqual(result, new URL('http://test-gateway.net'));
13
+ });
14
+ });
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PriorityGatewayRouter = void 0;
4
+ const random_js_1 = require("../../../utils/random.js");
5
+ // TODO: one of N where N are in the last time window have met certain performance thresholds
6
+ // TODO: look at bitorrent routing protocols for inspiration
7
+ // TODO: router that looks at local stats/metrics and adjusts based on those
8
+ class PriorityGatewayRouter {
9
+ name = 'priority';
10
+ gatewaysProvider;
11
+ limit;
12
+ sortBy;
13
+ sortOrder;
14
+ blocklist;
15
+ constructor({ gatewaysProvider, limit = 1, sortBy = 'operatorStake', sortOrder = 'desc', blocklist = [], }) {
16
+ this.gatewaysProvider = gatewaysProvider;
17
+ this.limit = limit;
18
+ this.sortBy = sortBy;
19
+ this.sortOrder = sortOrder;
20
+ this.blocklist = blocklist;
21
+ }
22
+ async getTargetGateway() {
23
+ const allGateways = await this.gatewaysProvider.getGateways();
24
+ const gateways = allGateways.filter((gateway) => gateway.status === 'joined' &&
25
+ !this.blocklist.includes(gateway.settings.fqdn));
26
+ const sortedGateways = gateways
27
+ .sort(this.sortOrder === 'asc'
28
+ ? (a, b) => a[this.sortBy] - b[this.sortBy]
29
+ : (a, b) => b[this.sortBy] - a[this.sortBy])
30
+ .slice(0, this.limit);
31
+ const targetGateway = sortedGateways[(0, random_js_1.randomInt)(0, sortedGateways.length)];
32
+ if (targetGateway === undefined) {
33
+ throw new Error('No target gateway found');
34
+ }
35
+ return new URL(`${targetGateway.settings.protocol}://${targetGateway.settings.fqdn}:${targetGateway.settings.port}`);
36
+ }
37
+ }
38
+ exports.PriorityGatewayRouter = PriorityGatewayRouter;
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_assert_1 = require("node:assert");
4
+ const node_test_1 = require("node:test");
5
+ const priority_js_1 = require("./priority.js");
6
+ (0, node_test_1.describe)('PriorityRouter', () => {
7
+ const mockGateways = [
8
+ {
9
+ settings: {
10
+ fqdn: 'gateway1.net',
11
+ port: 443,
12
+ protocol: 'https',
13
+ allowDelegatedStaking: false,
14
+ delegateRewardShareRatio: 0.5,
15
+ allowedDelegates: [],
16
+ minDelegatedStake: 0,
17
+ autoStake: false,
18
+ properties: '',
19
+ label: '',
20
+ note: '',
21
+ },
22
+ gatewayAddress: 'addr1',
23
+ observerAddress: 'addr1',
24
+ totalDelegatedStake: 1000,
25
+ startTimestamp: 0,
26
+ endTimestamp: 0,
27
+ operatorStake: 100,
28
+ status: 'joined',
29
+ weights: {
30
+ normalizedCompositeWeight: 0.5,
31
+ stakeWeight: 0.5,
32
+ tenureWeight: 0.5,
33
+ gatewayPerformanceRatio: 0.5,
34
+ observerPerformanceRatio: 0.5,
35
+ compositeWeight: 0.5,
36
+ gatewayRewardRatioWeight: 0.5,
37
+ observerRewardRatioWeight: 0.5,
38
+ },
39
+ stats: {
40
+ passedConsecutiveEpochs: 10,
41
+ failedConsecutiveEpochs: 5,
42
+ totalEpochCount: 15,
43
+ passedEpochCount: 10,
44
+ failedEpochCount: 5,
45
+ observedEpochCount: 15,
46
+ prescribedEpochCount: 20,
47
+ },
48
+ },
49
+ {
50
+ settings: {
51
+ fqdn: 'gateway1.net',
52
+ port: 443,
53
+ protocol: 'https',
54
+ allowDelegatedStaking: false,
55
+ delegateRewardShareRatio: 0.5,
56
+ allowedDelegates: [],
57
+ minDelegatedStake: 0,
58
+ autoStake: false,
59
+ properties: '',
60
+ label: '',
61
+ note: '',
62
+ },
63
+ gatewayAddress: 'addr1',
64
+ observerAddress: 'addr1',
65
+ totalDelegatedStake: 2000,
66
+ startTimestamp: 0,
67
+ endTimestamp: 0,
68
+ operatorStake: 2000,
69
+ status: 'joined',
70
+ weights: {
71
+ normalizedCompositeWeight: 0.5,
72
+ stakeWeight: 0.5,
73
+ tenureWeight: 0.5,
74
+ gatewayPerformanceRatio: 0.5,
75
+ observerPerformanceRatio: 0.5,
76
+ compositeWeight: 0.5,
77
+ gatewayRewardRatioWeight: 0.5,
78
+ observerRewardRatioWeight: 0.5,
79
+ },
80
+ stats: {
81
+ passedConsecutiveEpochs: 10,
82
+ failedConsecutiveEpochs: 5,
83
+ totalEpochCount: 15,
84
+ passedEpochCount: 10,
85
+ failedEpochCount: 5,
86
+ observedEpochCount: 15,
87
+ prescribedEpochCount: 20,
88
+ },
89
+ },
90
+ {
91
+ settings: {
92
+ fqdn: 'gateway2.net',
93
+ port: 443,
94
+ protocol: 'https',
95
+ allowDelegatedStaking: false,
96
+ delegateRewardShareRatio: 0.5,
97
+ allowedDelegates: [],
98
+ minDelegatedStake: 0,
99
+ autoStake: false,
100
+ properties: '',
101
+ label: '',
102
+ note: '',
103
+ },
104
+ gatewayAddress: 'addr2',
105
+ observerAddress: 'addr2',
106
+ totalDelegatedStake: 0,
107
+ startTimestamp: 0,
108
+ endTimestamp: 0,
109
+ operatorStake: 0,
110
+ status: 'leaving',
111
+ weights: {
112
+ normalizedCompositeWeight: 0.5,
113
+ stakeWeight: 0.5,
114
+ tenureWeight: 0.5,
115
+ gatewayPerformanceRatio: 0.5,
116
+ observerPerformanceRatio: 0.5,
117
+ compositeWeight: 0.5,
118
+ gatewayRewardRatioWeight: 0.5,
119
+ observerRewardRatioWeight: 0.5,
120
+ },
121
+ stats: {
122
+ passedConsecutiveEpochs: 10,
123
+ failedConsecutiveEpochs: 5,
124
+ totalEpochCount: 15,
125
+ passedEpochCount: 10,
126
+ failedEpochCount: 5,
127
+ observedEpochCount: 15,
128
+ prescribedEpochCount: 20,
129
+ },
130
+ },
131
+ ];
132
+ const mockGatewaysProvider = {
133
+ getGateways: async () => mockGateways,
134
+ };
135
+ (0, node_test_1.it)('should prioritize gateway with highest success rate when using successRate weight', async () => {
136
+ const router = new priority_js_1.PriorityGatewayRouter({
137
+ gatewaysProvider: mockGatewaysProvider,
138
+ sortBy: 'totalDelegatedStake',
139
+ sortOrder: 'desc',
140
+ limit: 1,
141
+ });
142
+ const result = await router.getTargetGateway();
143
+ node_assert_1.strict.deepStrictEqual(result, new URL('http://gateway1.net'));
144
+ });
145
+ (0, node_test_1.it)('should prioritize gateway with lowest latency when using latency weight', async () => {
146
+ const router = new priority_js_1.PriorityGatewayRouter({
147
+ gatewaysProvider: mockGatewaysProvider,
148
+ sortBy: 'operatorStake',
149
+ sortOrder: 'desc',
150
+ limit: 1,
151
+ });
152
+ const result = await router.getTargetGateway();
153
+ node_assert_1.strict.deepStrictEqual(result, new URL('http://gateway2.net'));
154
+ });
155
+ });
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RandomGatewayRouter = void 0;
4
+ const random_js_1 = require("../../../utils/random.js");
5
+ class RandomGatewayRouter {
6
+ name = 'random';
7
+ gatewaysProvider;
8
+ blocklist;
9
+ constructor({ gatewaysProvider, blocklist = [], }) {
10
+ this.gatewaysProvider = gatewaysProvider;
11
+ this.blocklist = blocklist;
12
+ }
13
+ async getTargetGateway() {
14
+ const allGateways = await this.gatewaysProvider.getGateways();
15
+ const gateways = allGateways.filter((g) => g.status === 'joined' && !this.blocklist.includes(g.settings.fqdn));
16
+ const targetGateway = gateways[(0, random_js_1.randomInt)(0, gateways.length)];
17
+ if (targetGateway === undefined) {
18
+ throw new Error('No target gateway found');
19
+ }
20
+ return new URL(`${targetGateway.settings.protocol}://${targetGateway.settings.fqdn}:${targetGateway.settings.port}`);
21
+ }
22
+ }
23
+ exports.RandomGatewayRouter = RandomGatewayRouter;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_assert_1 = require("node:assert");
4
+ const node_test_1 = require("node:test");
5
+ const random_js_1 = require("./random.js");
6
+ (0, node_test_1.describe)('RandomRouter', () => {
7
+ const mockGateways = [
8
+ {
9
+ settings: {
10
+ fqdn: 'gateway1.net',
11
+ port: 443,
12
+ protocol: 'https',
13
+ allowDelegatedStaking: false,
14
+ delegateRewardShareRatio: 0.5,
15
+ allowedDelegates: [],
16
+ minDelegatedStake: 0,
17
+ autoStake: false,
18
+ properties: '',
19
+ label: '',
20
+ note: '',
21
+ },
22
+ gatewayAddress: 'addr1',
23
+ observerAddress: 'addr1',
24
+ totalDelegatedStake: 1000,
25
+ startTimestamp: 0,
26
+ endTimestamp: 0,
27
+ operatorStake: 100,
28
+ status: 'joined',
29
+ weights: {
30
+ normalizedCompositeWeight: 0.5,
31
+ stakeWeight: 0.5,
32
+ tenureWeight: 0.5,
33
+ gatewayPerformanceRatio: 0.5,
34
+ observerPerformanceRatio: 0.5,
35
+ compositeWeight: 0.5,
36
+ gatewayRewardRatioWeight: 0.5,
37
+ observerRewardRatioWeight: 0.5,
38
+ },
39
+ stats: {
40
+ passedConsecutiveEpochs: 10,
41
+ failedConsecutiveEpochs: 5,
42
+ totalEpochCount: 15,
43
+ passedEpochCount: 10,
44
+ failedEpochCount: 5,
45
+ observedEpochCount: 15,
46
+ prescribedEpochCount: 20,
47
+ },
48
+ },
49
+ {
50
+ settings: {
51
+ fqdn: 'gateway2.net',
52
+ port: 443,
53
+ protocol: 'https',
54
+ allowDelegatedStaking: false,
55
+ delegateRewardShareRatio: 0.5,
56
+ allowedDelegates: [],
57
+ minDelegatedStake: 0,
58
+ autoStake: false,
59
+ properties: '',
60
+ label: '',
61
+ note: '',
62
+ },
63
+ gatewayAddress: 'addr2',
64
+ observerAddress: 'addr2',
65
+ totalDelegatedStake: 0,
66
+ startTimestamp: 0,
67
+ endTimestamp: 0,
68
+ operatorStake: 0,
69
+ status: 'leaving',
70
+ weights: {
71
+ normalizedCompositeWeight: 0.5,
72
+ stakeWeight: 0.5,
73
+ tenureWeight: 0.5,
74
+ gatewayPerformanceRatio: 0.5,
75
+ observerPerformanceRatio: 0.5,
76
+ compositeWeight: 0.5,
77
+ gatewayRewardRatioWeight: 0.5,
78
+ observerRewardRatioWeight: 0.5,
79
+ },
80
+ stats: {
81
+ passedConsecutiveEpochs: 10,
82
+ failedConsecutiveEpochs: 5,
83
+ totalEpochCount: 15,
84
+ passedEpochCount: 10,
85
+ failedEpochCount: 5,
86
+ observedEpochCount: 15,
87
+ prescribedEpochCount: 20,
88
+ },
89
+ },
90
+ ];
91
+ const mockGatewaysProvider = {
92
+ getGateways: async () => mockGateways,
93
+ };
94
+ (0, node_test_1.it)('should only return joined gateways', async () => {
95
+ const router = new random_js_1.RandomGatewayRouter({
96
+ gatewaysProvider: mockGatewaysProvider,
97
+ });
98
+ // Run multiple times to ensure we only get joined gateways
99
+ for (let i = 0; i < 10; i++) {
100
+ const result = await router.getTargetGateway();
101
+ node_assert_1.strict.deepStrictEqual(result, new URL('https://gateway1.net'));
102
+ }
103
+ });
104
+ });
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleCacheRouter = void 0;
4
+ class SimpleCacheRouter {
5
+ name;
6
+ lastUpdatedTimestamp;
7
+ ttlSeconds;
8
+ targetGateway;
9
+ router;
10
+ constructor({ router, ttlSeconds = 5 * 60, // 5 minutes
11
+ }) {
12
+ this.router = router;
13
+ this.ttlSeconds = ttlSeconds;
14
+ }
15
+ async getTargetGateway() {
16
+ if (this.targetGateway === undefined ||
17
+ this.lastUpdatedTimestamp + this.ttlSeconds * 1000 < Date.now()) {
18
+ this.targetGateway = await this.router.getTargetGateway();
19
+ this.lastUpdatedTimestamp = Date.now();
20
+ }
21
+ return this.targetGateway;
22
+ }
23
+ }
24
+ exports.SimpleCacheRouter = SimpleCacheRouter;
25
+ // TODO: a router that accepts ario and a router, and adds read through promise cache to ario.getGateways to avoid calling the ARIO contract on every request
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_assert_1 = require("node:assert");
4
+ const node_test_1 = require("node:test");
5
+ const simple_cache_js_1 = require("./simple-cache.js");
6
+ (0, node_test_1.describe)('SimpleCacheRouter', () => {
7
+ (0, node_test_1.it)('should cache gateway for TTL period even if underlying gateway changes', async () => {
8
+ const gateway1 = new URL('https://gateway1.net');
9
+ const gateway2 = new URL('https://gateway2.net');
10
+ let currentGateway = gateway1;
11
+ const mockRouter = {
12
+ name: 'mock',
13
+ getTargetGateway: async () => currentGateway,
14
+ };
15
+ const router = new simple_cache_js_1.SimpleCacheRouter({
16
+ router: mockRouter,
17
+ ttlSeconds: 300, // 5 minutes
18
+ });
19
+ // Get initial gateway which should be cached
20
+ const initial = await router.getTargetGateway();
21
+ node_assert_1.strict.deepStrictEqual(initial, gateway1);
22
+ // Change the underlying gateway
23
+ currentGateway = gateway2;
24
+ // Should still return cached gateway1 for multiple calls
25
+ for (let i = 0; i < 5; i++) {
26
+ const result = await router.getTargetGateway();
27
+ node_assert_1.strict.deepStrictEqual(result, gateway1);
28
+ }
29
+ // Advance time past TTL
30
+ const originalNow = Date.now;
31
+ try {
32
+ Date.now = () => originalNow() + 300 * 1000 + 1;
33
+ // Should now return the new gateway2
34
+ const result = await router.getTargetGateway();
35
+ node_assert_1.strict.deepStrictEqual(result, gateway2);
36
+ }
37
+ finally {
38
+ Date.now = originalNow;
39
+ }
40
+ });
41
+ });
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Wayfinder = exports.createWayfinderClient = exports.resolveWayfinderUrl = exports.txIdRegex = exports.arnsRegex = void 0;
4
+ const io_js_1 = require("../io.js");
5
+ const gateways_js_1 = require("./gateways.js");
6
+ const random_js_1 = require("./routers/random.js");
7
+ // known regexes for wayfinder urls
8
+ exports.arnsRegex = /^[a-z0-9_-]{1,51}$/;
9
+ exports.txIdRegex = /^[a-z0-9]{43}$/;
10
+ /**
11
+ * Core function to resolve a wayfinder url against a target gateway
12
+ * @param originalUrl - the wayfinder url to resolve
13
+ * @param targetGateway - the target gateway to resolve the url against
14
+ * @returns the resolved url that can be used to make a request
15
+ */
16
+ const resolveWayfinderUrl = ({ originalUrl, targetGateway, }) => {
17
+ if (originalUrl.toString().startsWith('ar://')) {
18
+ const [, path] = originalUrl.toString().split('ar://');
19
+ // e.g. ar:///info should route to the info endpoint of the target gateway
20
+ if (path.startsWith('/')) {
21
+ return new URL(path.slice(1), targetGateway);
22
+ }
23
+ // TODO: this breaks 43 character named arns names - we should check a a local name cache list before resolving raw transaction ids
24
+ if (exports.txIdRegex.test(path)) {
25
+ const [txId, ...rest] = path.split('/');
26
+ return new URL(`${txId}${rest.join('/')}`, targetGateway);
27
+ }
28
+ if (exports.arnsRegex.test(path)) {
29
+ // TODO: tests to ensure arns names support query params and paths
30
+ const [name, ...rest] = path.split('/');
31
+ const targetGatewayUrl = new URL(targetGateway);
32
+ const arnsUrl = `${targetGatewayUrl.protocol}//${name}.${targetGatewayUrl.hostname}${targetGatewayUrl.port ? `:${targetGatewayUrl.port}` : ''}`;
33
+ return new URL(rest.join('/'), arnsUrl);
34
+ }
35
+ // TODO: support .eth addresses
36
+ // TODO: "gasless" routing via DNS TXT records (e.g. ar://gatewaypie.com -> TXT record lookup for TX ID and redirect to that gateway)
37
+ }
38
+ // return the original url if it's not a wayfinder url (allows you to use the wayfinder client with non-wayfinder urls)
39
+ return new URL(originalUrl);
40
+ };
41
+ exports.resolveWayfinderUrl = resolveWayfinderUrl;
42
+ /**
43
+ * Creates a wrapped http client that supports ar:// protocol
44
+ *
45
+ * This function leverages a Proxy to intercept calls to the http client
46
+ * and redirects them to the target gateway using the resolveUrl function url.
47
+ * It also supports the http client methods like get(), post(), put(), delete(), etc.
48
+ *
49
+ * Any URLs provided that are not wayfinder urls will be returned as is.
50
+ *
51
+ * @param httpClient - the http client to wrap (e.g. axios, fetch, got, etc.)
52
+ * @param resolveUrl - the function to construct the redirect url for ar:// requests
53
+ * @returns a wrapped http client that supports ar:// protocol
54
+ */
55
+ const createWayfinderClient = ({ httpClient, resolveUrl, }) => {
56
+ const wayfinderRedirect = async (fn, rawArgs) => {
57
+ // TODO: handle if first arg is not a string (i.e. just return the result of the function call)
58
+ const [originalUrl, ...rest] = rawArgs;
59
+ // route the request to the target gateway
60
+ const redirectUrl = await resolveUrl({
61
+ originalUrl,
62
+ });
63
+ // make the request to the target gateway using the redirect url and http client
64
+ const response = await fn(redirectUrl.toString(), ...rest);
65
+ // TODO: if verifyDataHash is provided, verify the data hash before returning
66
+ return response;
67
+ };
68
+ return new Proxy(httpClient, {
69
+ // support direct calls: fetch('ar://…', options)
70
+ // axios() or got()
71
+ apply: (_target, _thisArg, argArray) => wayfinderRedirect(httpClient, argArray),
72
+ // support http clients that use methods like `got.get`, `got.post`, `axios.get`, etc. while still using the wayfinder redirect function
73
+ get: (target, prop, receiver) => {
74
+ const value = Reflect.get(target, prop, receiver);
75
+ if (typeof value === 'function') {
76
+ return (...inner) => wayfinderRedirect(value.bind(target), inner);
77
+ }
78
+ return value; // numbers, objects, symbols pass through untouched
79
+ },
80
+ });
81
+ };
82
+ exports.createWayfinderClient = createWayfinderClient;
83
+ /**
84
+ * The main class for the wayfinder
85
+ * @param router - the router to use for requests
86
+ * @param httpClient - the http client to use for requests
87
+ * @param blocklist - the blocklist of gateways to avoid
88
+ */
89
+ class Wayfinder {
90
+ /**
91
+ * The router to use for requests
92
+ *
93
+ * @example
94
+ * const wayfinder = new Wayfinder({
95
+ * router: new RandomGatewayRouter({
96
+ * gatewaysProvider: new ARIOGatewaysProvider({ ario: ARIO.mainnet() })
97
+ * }),
98
+ * });
99
+ */
100
+ router;
101
+ /**
102
+ * The http client to use for requests
103
+ *
104
+ * @example
105
+ * const wayfinder = new Wayfinder({
106
+ * router: new RandomGatewayRouter({
107
+ * gatewaysProvider: new ARIOGatewaysProvider({ ario: ARIO.mainnet() })
108
+ * }),
109
+ * httpClient: axios,
110
+ * });
111
+ */
112
+ httpClient;
113
+ /**
114
+ * The function that resolves the redirect url for ar:// requests to a target gateway
115
+ *
116
+ * @example
117
+ * const wayfinder = new Wayfinder({
118
+ * router: new RandomGatewayRouter({
119
+ * gatewaysProvider: new ARIOGatewaysProvider({ ario: ARIO.mainnet() })
120
+ * }),
121
+ * httpClient: axios,
122
+ * });
123
+ *
124
+ * const redirectUrl = await wayfinder.resolveUrl({ originalUrl: 'ar://example' });
125
+ */
126
+ resolveUrl;
127
+ /**
128
+ * A wrapped http client that supports ar:// protocol
129
+ *
130
+ * @example
131
+ * const { request: wayfind } = new Wayfinder({
132
+ * router: new RandomGatewayRouter({
133
+ * gatewaysProvider: new ARIOGatewaysProvider({ ario: ARIO.mainnet() })
134
+ * }),
135
+ * httpClient: axios,
136
+ * });;
137
+ *
138
+ * const response = await wayfind('ar://example', {
139
+ * method: 'POST',
140
+ * data: {
141
+ * name: 'John Doe',
142
+ * },
143
+ * })
144
+ */
145
+ request;
146
+ // TODO: stats provider
147
+ // TODO: metricsProvider for otel/prom support
148
+ // TODO: private verificationSettings: {
149
+ // trustedGateways: URL[];
150
+ // method: 'local' | 'remote';
151
+ // };
152
+ constructor({
153
+ // TODO: consider changing router to routingStrategy or strategy
154
+ router = new random_js_1.RandomGatewayRouter({
155
+ // optionally use a cache gateways provider to reduce the number of requests to the contract
156
+ gatewaysProvider: new gateways_js_1.ARIOGatewaysProvider({ ario: io_js_1.ARIO.mainnet() }),
157
+ }), httpClient,
158
+ // TODO: add verifier interface that provides a verifyDataHash function
159
+ // TODO: stats provider
160
+ }) {
161
+ this.router = router;
162
+ this.httpClient = httpClient;
163
+ this.resolveUrl = async ({ originalUrl }) => (0, exports.resolveWayfinderUrl)({
164
+ originalUrl,
165
+ targetGateway: await this.router.getTargetGateway(),
166
+ });
167
+ this.request = (0, exports.createWayfinderClient)({
168
+ httpClient,
169
+ resolveUrl: this.resolveUrl,
170
+ // TODO: provide the verifyDataHash function from the verifier to the wayfinder client along with verificationSettings
171
+ });
172
+ }
173
+ }
174
+ exports.Wayfinder = Wayfinder;