@le-space/browser 0.8.0 → 0.9.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 (3) hide show
  1. package/index.d.ts +127 -72
  2. package/index.js +141 -2
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -1,3 +1,120 @@
1
+ declare const DEFAULT_ALEPH_API_HOSTS: readonly string[];
2
+ declare const DEFAULT_ALEPH_API_HOST: string;
3
+ declare const DEFAULT_CRN_LIST_URL = "https://crns-list.aleph.sh/crns.json";
4
+ declare const DEFAULT_CRN_AGGREGATE_ADDRESS = "0xa1B3bb7d2332383D96b7796B908fB7f7F3c2Be10";
5
+ declare const DEFAULT_CRN_AGGREGATE_KEY = "corechannel";
6
+ type CrnSource = 'list' | 'aggregate';
7
+ declare const DEFAULT_ALEPH_SCHEDULER_API_HOST = "https://scheduler.api.aleph.cloud";
8
+ declare const DEFAULT_2N6_API_HOST = "https://api.2n6.me";
9
+ type CrnExecutionV1Payload = {
10
+ networking?: {
11
+ ipv4?: unknown;
12
+ ipv6?: unknown;
13
+ } | null;
14
+ };
15
+ type CrnExecutionV2Payload = {
16
+ networking?: {
17
+ ipv4_network?: unknown;
18
+ host_ipv4?: unknown;
19
+ ipv6_network?: unknown;
20
+ ipv6_ip?: unknown;
21
+ ipv4_ip?: unknown;
22
+ proxy_url?: unknown;
23
+ proxyUrl?: unknown;
24
+ web_access_url?: unknown;
25
+ webAccessUrl?: unknown;
26
+ proxy_hostname?: unknown;
27
+ proxyHostname?: unknown;
28
+ domain?: unknown;
29
+ hostname?: unknown;
30
+ mapped_ports?: Record<string, {
31
+ host?: unknown;
32
+ tcp?: unknown;
33
+ udp?: unknown;
34
+ }> | null;
35
+ } | null;
36
+ web_access?: {
37
+ url?: unknown;
38
+ proxy_url?: unknown;
39
+ hostname?: unknown;
40
+ domain?: unknown;
41
+ } | null;
42
+ webAccess?: {
43
+ url?: unknown;
44
+ proxy_url?: unknown;
45
+ hostname?: unknown;
46
+ domain?: unknown;
47
+ } | null;
48
+ status?: {
49
+ defined_at?: unknown;
50
+ preparing_at?: unknown;
51
+ prepared_at?: unknown;
52
+ starting_at?: unknown;
53
+ started_at?: unknown;
54
+ stopping_at?: unknown;
55
+ stopped_at?: unknown;
56
+ } | null;
57
+ running?: unknown;
58
+ };
59
+ declare function normalizeMessageStatus(status: unknown): MessageStatus;
60
+ declare function fetchBalance(address: string, apiHost?: string): Promise<BalanceResponse>;
61
+ declare function fetchCrnsFromList(url?: string): Promise<Crn[]>;
62
+ declare function mapResourceNodesToCrns(resourceNodes: unknown): Crn[];
63
+ declare function fetchCrnsFromAggregate(apiHosts?: readonly string[], address?: string): Promise<Crn[]>;
64
+ interface FetchCrnsOptions {
65
+ apiHosts?: readonly string[];
66
+ aggregateAddress?: string;
67
+ /**
68
+ * `auto` prefers crns.json and falls back to the aggregate, `aggregate`
69
+ * reads the aggregate directly, `list` disables the fallback so an outage
70
+ * surfaces as an error. Useful for exercising either path deliberately.
71
+ */
72
+ source?: CrnSourcePreference;
73
+ }
74
+ type CrnSourcePreference = 'auto' | 'aggregate' | 'list';
75
+ interface CrnListResult {
76
+ crns: Crn[];
77
+ source: CrnSource;
78
+ listError?: Error;
79
+ }
80
+ /**
81
+ * Prefers the polled crns.json list for its live status, capacity and qemu
82
+ * flags, and falls back to the core channel aggregate when that single HTTP
83
+ * service is down — an outage that reaches the browser as a CORS error because
84
+ * the gateway's 502 page carries no Access-Control-Allow-Origin header.
85
+ */
86
+ declare function fetchCrnsWithSource(url?: string, options?: FetchCrnsOptions): Promise<CrnListResult>;
87
+ declare function fetchCrns(url?: string, options?: FetchCrnsOptions): Promise<Crn[]>;
88
+ /**
89
+ * `unknown` is not a soft `unreachable`: the browser cannot distinguish a node
90
+ * that is down from one whose CORS headers block us, and dropping candidates
91
+ * for our own origin restriction would be worse than not probing at all.
92
+ */
93
+ type CrnProbeVerdict = 'reachable' | 'unreachable' | 'unknown';
94
+ declare function probeCrnAvailability(crn: Pick<Crn, 'address'>): Promise<CrnProbeVerdict>;
95
+ /**
96
+ * Drops candidates that answered but are not serving, keeping the incoming
97
+ * order. Aggregate records carry no liveness signal, so without this a
98
+ * registered-but-dead node costs a full deployment attempt. Only the head is
99
+ * probed, and if every candidate is ruled out the list is returned unchanged.
100
+ */
101
+ declare function filterReachableCrns<TCrn extends Crn>(crns: readonly TCrn[], options?: {
102
+ limit?: number;
103
+ onDiagnostic?: (message: string) => void;
104
+ }): Promise<TCrn[]>;
105
+ declare function fetchInstances(address: string, apiHost?: string): Promise<InstanceMessage[]>;
106
+ declare function fetch2n6WebAccessUrl(itemHash: string, twoN6ApiHost?: string): Promise<string | null>;
107
+ declare function fetchSchedulerAllocation(itemHash: string, schedulerApiHost?: string): Promise<InstanceAllocation | null>;
108
+ declare function fetchCrnExecutionMap(crnUrl: string): Promise<CrnExecutionLookupResult>;
109
+ declare function normalizeExecution(item: CrnExecutionV1Payload | CrnExecutionV2Payload, crnUrl: string): InstanceExecution;
110
+ declare function notifyCrnAllocation(crnUrl: string, itemHash: string): Promise<AllocationNotifyResult>;
111
+ declare function configureOrbitdbRelaySetup(args: RelaySetupRequest): Promise<RelaySetupResult>;
112
+ declare function fetchMessageEnvelope(itemHash: string, apiHost?: string): Promise<AlephMessageEnvelope | null>;
113
+ declare function inspectDeploymentResult(itemHash: string, rootfsRef?: string, apiHost?: string): Promise<DeploymentInspectionResult>;
114
+ declare function waitForDeploymentResult(itemHash: string, rootfsRef?: string, apiHost?: string, attempts?: number, delayMs?: number): Promise<DeploymentInspectionResult>;
115
+ declare function broadcastInstanceMessage(message: AlephBroadcastMessage, apiHost?: string, sync?: boolean): Promise<BroadcastResult>;
116
+ declare function broadcastAlephMessage(message: AlephBroadcastMessage, apiHost?: string, sync?: boolean): Promise<BroadcastResult>;
117
+
1
118
  type BrowserExtractionPhase = 'planned' | 'scaffolded';
2
119
  interface BrowserPackagePlan {
3
120
  phase: BrowserExtractionPhase;
@@ -283,9 +400,13 @@ interface AlephBrowserClient {
283
400
  apiHost: string;
284
401
  apiHosts: string[];
285
402
  crnListUrl: string;
403
+ /** Which CRN source the client is configured to read. */
404
+ crnSource: CrnSourcePreference;
286
405
  schedulerApiHost: string;
287
406
  fetchBalance(address: string): Promise<BalanceResponse>;
288
407
  fetchCrns(): Promise<Crn[]>;
408
+ /** `source` overrides the configured preference for this call, so a live toggle takes effect without rebuilding the client. */
409
+ fetchCrnsWithSource(source?: CrnSourcePreference): Promise<CrnListResult>;
289
410
  fetchInstances(address: string): Promise<InstanceMessage[]>;
290
411
  fetch2n6WebAccessUrl(itemHash: string): Promise<string | null>;
291
412
  fetchMessageEnvelope(itemHash: string): Promise<AlephMessageEnvelope | null>;
@@ -347,82 +468,16 @@ interface RootfsResolution {
347
468
 
348
469
  declare function fetchWithTimeout(input: RequestInfo | URL, init?: RequestInit, timeoutMs?: number): Promise<Response>;
349
470
 
350
- declare const DEFAULT_ALEPH_API_HOSTS: readonly string[];
351
- declare const DEFAULT_ALEPH_API_HOST: string;
352
- declare const DEFAULT_CRN_LIST_URL = "https://crns-list.aleph.sh/crns.json";
353
- declare const DEFAULT_ALEPH_SCHEDULER_API_HOST = "https://scheduler.api.aleph.cloud";
354
- declare const DEFAULT_2N6_API_HOST = "https://api.2n6.me";
355
- type CrnExecutionV1Payload = {
356
- networking?: {
357
- ipv4?: unknown;
358
- ipv6?: unknown;
359
- } | null;
360
- };
361
- type CrnExecutionV2Payload = {
362
- networking?: {
363
- ipv4_network?: unknown;
364
- host_ipv4?: unknown;
365
- ipv6_network?: unknown;
366
- ipv6_ip?: unknown;
367
- ipv4_ip?: unknown;
368
- proxy_url?: unknown;
369
- proxyUrl?: unknown;
370
- web_access_url?: unknown;
371
- webAccessUrl?: unknown;
372
- proxy_hostname?: unknown;
373
- proxyHostname?: unknown;
374
- domain?: unknown;
375
- hostname?: unknown;
376
- mapped_ports?: Record<string, {
377
- host?: unknown;
378
- tcp?: unknown;
379
- udp?: unknown;
380
- }> | null;
381
- } | null;
382
- web_access?: {
383
- url?: unknown;
384
- proxy_url?: unknown;
385
- hostname?: unknown;
386
- domain?: unknown;
387
- } | null;
388
- webAccess?: {
389
- url?: unknown;
390
- proxy_url?: unknown;
391
- hostname?: unknown;
392
- domain?: unknown;
393
- } | null;
394
- status?: {
395
- defined_at?: unknown;
396
- preparing_at?: unknown;
397
- prepared_at?: unknown;
398
- starting_at?: unknown;
399
- started_at?: unknown;
400
- stopping_at?: unknown;
401
- stopped_at?: unknown;
402
- } | null;
403
- running?: unknown;
404
- };
405
- declare function normalizeMessageStatus(status: unknown): MessageStatus;
406
- declare function fetchBalance(address: string, apiHost?: string): Promise<BalanceResponse>;
407
- declare function fetchCrns(url?: string): Promise<Crn[]>;
408
- declare function fetchInstances(address: string, apiHost?: string): Promise<InstanceMessage[]>;
409
- declare function fetch2n6WebAccessUrl(itemHash: string, twoN6ApiHost?: string): Promise<string | null>;
410
- declare function fetchSchedulerAllocation(itemHash: string, schedulerApiHost?: string): Promise<InstanceAllocation | null>;
411
- declare function fetchCrnExecutionMap(crnUrl: string): Promise<CrnExecutionLookupResult>;
412
- declare function normalizeExecution(item: CrnExecutionV1Payload | CrnExecutionV2Payload, crnUrl: string): InstanceExecution;
413
- declare function notifyCrnAllocation(crnUrl: string, itemHash: string): Promise<AllocationNotifyResult>;
414
- declare function configureOrbitdbRelaySetup(args: RelaySetupRequest): Promise<RelaySetupResult>;
415
- declare function fetchMessageEnvelope(itemHash: string, apiHost?: string): Promise<AlephMessageEnvelope | null>;
416
- declare function inspectDeploymentResult(itemHash: string, rootfsRef?: string, apiHost?: string): Promise<DeploymentInspectionResult>;
417
- declare function waitForDeploymentResult(itemHash: string, rootfsRef?: string, apiHost?: string, attempts?: number, delayMs?: number): Promise<DeploymentInspectionResult>;
418
- declare function broadcastInstanceMessage(message: AlephBroadcastMessage, apiHost?: string, sync?: boolean): Promise<BroadcastResult>;
419
- declare function broadcastAlephMessage(message: AlephBroadcastMessage, apiHost?: string, sync?: boolean): Promise<BroadcastResult>;
420
-
421
471
  type ApiHostInput = string | readonly string[];
422
472
  interface CreateAlephBrowserClientOptions {
423
473
  apiHost?: string;
424
474
  apiHosts?: ApiHostInput;
425
475
  crnListUrl?: string;
476
+ /**
477
+ * `auto` falls back to the corechannel aggregate when crns.json is down,
478
+ * `aggregate` skips crns.json, `list` disables the fallback.
479
+ */
480
+ crnSource?: CrnSourcePreference;
426
481
  schedulerApiHost?: string;
427
482
  twoN6ApiHost?: string;
428
483
  }
@@ -496,4 +551,4 @@ declare const DEFAULT_ALEPH_AGGREGATE_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e
496
551
  declare function parseInstancePricing(payload: unknown): InstancePricing;
497
552
  declare function fetchInstancePricing(apiHost?: string, aggregateAddress?: string): Promise<PricingState>;
498
553
 
499
- export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnLocation, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_API_HOSTS, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type EvmChainConfig, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentChain, type PaymentMode, type PrepaidReservation, type PrepaidVaultSnapshot, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, approvePrepaidBudget, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, consumeDeploymentReservation, createAlephBrowserClient, depositPrepaidBudget, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, formatBudgetUnits, inspectDeploymentResult, loadPrepaidReservation, loadPrepaidVaultSnapshot, loadRootfsManifest, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, paymentChainFromChainId, personalSign, refundExpiredReservation, reserveDeploymentBudget, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult };
554
+ export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnListResult, type CrnLocation, type CrnProbeVerdict, type CrnSource, type CrnSourcePreference, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_API_HOSTS, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_AGGREGATE_ADDRESS, DEFAULT_CRN_AGGREGATE_KEY, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type EvmChainConfig, type FetchCrnsOptions, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentChain, type PaymentMode, type PrepaidReservation, type PrepaidVaultSnapshot, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, approvePrepaidBudget, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, consumeDeploymentReservation, createAlephBrowserClient, depositPrepaidBudget, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchCrnsFromAggregate, fetchCrnsFromList, fetchCrnsWithSource, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, filterReachableCrns, formatBudgetUnits, inspectDeploymentResult, loadPrepaidReservation, loadPrepaidVaultSnapshot, loadRootfsManifest, mapResourceNodesToCrns, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, paymentChainFromChainId, personalSign, probeCrnAvailability, refundExpiredReservation, reserveDeploymentBudget, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult };
package/index.js CHANGED
@@ -54,6 +54,8 @@ var DEFAULT_ALEPH_API_HOSTS = [
54
54
  ];
55
55
  var DEFAULT_ALEPH_API_HOST = DEFAULT_ALEPH_API_HOSTS[0] ?? "https://api2.aleph.im";
56
56
  var DEFAULT_CRN_LIST_URL = "https://crns-list.aleph.sh/crns.json";
57
+ var DEFAULT_CRN_AGGREGATE_ADDRESS = "0xa1B3bb7d2332383D96b7796B908fB7f7F3c2Be10";
58
+ var DEFAULT_CRN_AGGREGATE_KEY = "corechannel";
57
59
  var DEFAULT_ALEPH_SCHEDULER_API_HOST = "https://scheduler.api.aleph.cloud";
58
60
  var DEFAULT_2N6_API_HOST = "https://api.2n6.me";
59
61
  function normalizeMessageStatus(status) {
@@ -108,7 +110,7 @@ async function fetchBalance(address, apiHost = DEFAULT_ALEPH_API_HOST) {
108
110
  if (!response.ok) throw new Error(`Balance request failed: ${response.status}`);
109
111
  return await response.json();
110
112
  }
111
- async function fetchCrns(url = DEFAULT_CRN_LIST_URL) {
113
+ async function fetchCrnsFromList(url = DEFAULT_CRN_LIST_URL) {
112
114
  const requestUrl = new URL(url);
113
115
  requestUrl.searchParams.set("filter_inactive", "true");
114
116
  const response = await fetchWithTimeout(requestUrl, { cache: "no-cache" });
@@ -116,6 +118,130 @@ async function fetchCrns(url = DEFAULT_CRN_LIST_URL) {
116
118
  const payload = await response.json();
117
119
  return payload.crns ?? [];
118
120
  }
121
+ function asFiniteNumber(value) {
122
+ if (value == null || value === "") return null;
123
+ const numeric = typeof value === "number" ? value : Number(value);
124
+ return Number.isFinite(numeric) ? numeric : null;
125
+ }
126
+ function normalizeCrnAddress(value) {
127
+ const address = asString(value);
128
+ if (!address) return null;
129
+ const withScheme = /^https?:\/\//i.test(address) ? address : `https://${address}`;
130
+ try {
131
+ return new URL(withScheme).toString().replace(/\/+$/, "");
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ function mapResourceNodesToCrns(resourceNodes) {
137
+ if (!Array.isArray(resourceNodes)) return [];
138
+ const crns = [];
139
+ for (const node of resourceNodes) {
140
+ if (!node || typeof node !== "object") continue;
141
+ const entry = node;
142
+ const hash = asString(entry.hash);
143
+ const address = normalizeCrnAddress(entry.address);
144
+ const type = asString(entry.type)?.toLowerCase();
145
+ const status = asString(entry.status)?.toLowerCase();
146
+ if (!hash || !address) continue;
147
+ if (entry.inactive_since != null || entry.locked === true) continue;
148
+ if (type && type !== "compute") continue;
149
+ if (status && status !== "linked" && status !== "active") continue;
150
+ if (!asString(entry.parent)) continue;
151
+ const score = asFiniteNumber(entry.score) ?? asFiniteNumber(entry.scoreV1);
152
+ const performance = asFiniteNumber(entry.performance);
153
+ const decentralization = asFiniteNumber(entry.decentralization);
154
+ crns.push({
155
+ hash,
156
+ address,
157
+ name: asString(entry.name) ?? hash,
158
+ ...score == null ? {} : { score },
159
+ ...performance == null ? {} : { performance },
160
+ ...decentralization == null ? {} : { decentralization }
161
+ });
162
+ }
163
+ return crns;
164
+ }
165
+ async function fetchCrnsFromAggregate(apiHosts = DEFAULT_ALEPH_API_HOSTS, address = DEFAULT_CRN_AGGREGATE_ADDRESS) {
166
+ const hosts = apiHosts.length > 0 ? apiHosts : DEFAULT_ALEPH_API_HOSTS;
167
+ let lastError = null;
168
+ for (const apiHost of hosts) {
169
+ try {
170
+ const url = new URL(`/api/v0/aggregates/${address}.json`, apiHost);
171
+ url.searchParams.set("keys", DEFAULT_CRN_AGGREGATE_KEY);
172
+ const response = await fetchWithTimeout(url, { cache: "no-cache" });
173
+ if (!response.ok) {
174
+ lastError = new Error(`CRN aggregate request failed: ${response.status}`);
175
+ continue;
176
+ }
177
+ const payload = await response.json();
178
+ const crns = mapResourceNodesToCrns(payload?.data?.corechannel?.resource_nodes);
179
+ if (crns.length > 0) return crns;
180
+ lastError = new Error("CRN aggregate contained no deployable resource nodes");
181
+ } catch (error) {
182
+ lastError = error;
183
+ }
184
+ }
185
+ throw lastError instanceof Error ? lastError : new Error(String(lastError ?? "CRN aggregate request failed"));
186
+ }
187
+ async function fetchCrnsWithSource(url = DEFAULT_CRN_LIST_URL, options = {}) {
188
+ const apiHosts = options.apiHosts ?? DEFAULT_ALEPH_API_HOSTS;
189
+ const source = options.source ?? "auto";
190
+ if (source === "aggregate") {
191
+ return {
192
+ crns: await fetchCrnsFromAggregate(apiHosts, options.aggregateAddress),
193
+ source: "aggregate"
194
+ };
195
+ }
196
+ let listError;
197
+ try {
198
+ const crns = await fetchCrnsFromList(url);
199
+ if (crns.length > 0) return { crns, source: "list" };
200
+ listError = new Error("CRN list returned no entries");
201
+ } catch (error) {
202
+ listError = error instanceof Error ? error : new Error(String(error));
203
+ }
204
+ if (source === "list") throw listError;
205
+ return {
206
+ crns: await fetchCrnsFromAggregate(apiHosts, options.aggregateAddress),
207
+ source: "aggregate",
208
+ listError
209
+ };
210
+ }
211
+ async function fetchCrns(url = DEFAULT_CRN_LIST_URL, options = {}) {
212
+ return (await fetchCrnsWithSource(url, options)).crns;
213
+ }
214
+ async function probeCrnAvailability(crn) {
215
+ const address = String(crn.address ?? "").trim();
216
+ if (!address) return "unreachable";
217
+ const lookup = await fetchCrnExecutionMap(address);
218
+ if (lookup.payload !== null) return "reachable";
219
+ return lookup.blocked ? "unknown" : "unreachable";
220
+ }
221
+ async function filterReachableCrns(crns, options = {}) {
222
+ const limit = Math.max(1, Number(options.limit) || 5);
223
+ const probed = crns.slice(0, limit);
224
+ if (probed.length === 0) return [...crns];
225
+ const verdicts = await Promise.all(
226
+ probed.map(async (crn) => {
227
+ try {
228
+ return { crn, verdict: await probeCrnAvailability(crn) };
229
+ } catch {
230
+ return { crn, verdict: "unknown" };
231
+ }
232
+ })
233
+ );
234
+ const kept = verdicts.filter((entry) => entry.verdict !== "unreachable").map((entry) => entry.crn);
235
+ if (kept.length === 0) {
236
+ options.onDiagnostic?.(`No CRN answered its executions endpoint (${probed.length} probed); keeping the unverified order`);
237
+ return [...crns];
238
+ }
239
+ const dropped = probed.length - kept.length;
240
+ if (dropped > 0) {
241
+ options.onDiagnostic?.(`Skipping ${dropped} unreachable CRN${dropped === 1 ? "" : "s"} of ${probed.length} probed`);
242
+ }
243
+ return [...kept, ...crns.slice(limit)];
244
+ }
119
245
  async function fetchInstances(address, apiHost = DEFAULT_ALEPH_API_HOST) {
120
246
  const url = new URL("/api/v0/messages.json", apiHost);
121
247
  url.searchParams.set("msgTypes", "INSTANCE");
@@ -509,18 +635,23 @@ function createAlephBrowserClient(options = {}) {
509
635
  const apiHosts = options.apiHosts === void 0 && options.apiHost === void 0 ? [...DEFAULT_ALEPH_API_HOSTS] : normalizeApiHosts(options.apiHosts, options.apiHost ?? DEFAULT_ALEPH_API_HOST);
510
636
  const apiHost = apiHosts[0] ?? DEFAULT_ALEPH_API_HOST;
511
637
  const crnListUrl = options.crnListUrl ?? DEFAULT_CRN_LIST_URL;
638
+ const crnSource = options.crnSource ?? "auto";
512
639
  const schedulerApiHost = options.schedulerApiHost ?? DEFAULT_ALEPH_SCHEDULER_API_HOST;
513
640
  const twoN6ApiHost = options.twoN6ApiHost ?? DEFAULT_2N6_API_HOST;
514
641
  return {
515
642
  apiHost,
516
643
  apiHosts,
517
644
  crnListUrl,
645
+ crnSource,
518
646
  schedulerApiHost,
519
647
  fetchBalance(address) {
520
648
  return withApiHostFallback(apiHosts, (host) => fetchBalance(address, host));
521
649
  },
522
650
  fetchCrns() {
523
- return fetchCrns(crnListUrl);
651
+ return fetchCrns(crnListUrl, { apiHosts, source: crnSource });
652
+ },
653
+ fetchCrnsWithSource(source) {
654
+ return fetchCrnsWithSource(crnListUrl, { apiHosts, source: source ?? crnSource });
524
655
  },
525
656
  fetchInstances(address) {
526
657
  return withApiHostFallback(apiHosts, (host) => fetchInstances(address, host));
@@ -996,6 +1127,8 @@ export {
996
1127
  DEFAULT_ALEPH_API_HOST,
997
1128
  DEFAULT_ALEPH_API_HOSTS,
998
1129
  DEFAULT_ALEPH_SCHEDULER_API_HOST,
1130
+ DEFAULT_CRN_AGGREGATE_ADDRESS,
1131
+ DEFAULT_CRN_AGGREGATE_KEY,
999
1132
  DEFAULT_CRN_LIST_URL,
1000
1133
  DEFAULT_IPFS_GATEWAY_BASE_URL,
1001
1134
  DEFAULT_ROOTFS_MANIFEST_URL,
@@ -1012,22 +1145,28 @@ export {
1012
1145
  fetchBalance,
1013
1146
  fetchCrnExecutionMap,
1014
1147
  fetchCrns,
1148
+ fetchCrnsFromAggregate,
1149
+ fetchCrnsFromList,
1150
+ fetchCrnsWithSource,
1015
1151
  fetchInstancePricing,
1016
1152
  fetchInstances,
1017
1153
  fetchMessageEnvelope,
1018
1154
  fetchSchedulerAllocation,
1019
1155
  fetchWithTimeout,
1156
+ filterReachableCrns,
1020
1157
  formatBudgetUnits,
1021
1158
  inspectDeploymentResult,
1022
1159
  loadPrepaidReservation,
1023
1160
  loadPrepaidVaultSnapshot,
1024
1161
  loadRootfsManifest,
1162
+ mapResourceNodesToCrns,
1025
1163
  normalizeExecution,
1026
1164
  normalizeMessageStatus,
1027
1165
  notifyCrnAllocation,
1028
1166
  parseInstancePricing,
1029
1167
  paymentChainFromChainId,
1030
1168
  personalSign,
1169
+ probeCrnAvailability,
1031
1170
  refundExpiredReservation,
1032
1171
  reserveDeploymentBudget,
1033
1172
  resolveRootfsReference,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/browser",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "Shared browser-safe Aleph deployment and polling helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",