@platforma-sdk/block-tools 2.22.6 → 2.24.0

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.
@@ -16,6 +16,7 @@ import {
16
16
  import type { BlockKindReference } from "@milaboratories/pl-model-common";
17
17
  import { parseKindRef } from "@milaboratories/pl-model-common";
18
18
  import type { FolderReader } from "../../io";
19
+ import { isFileNotFound } from "../../io";
19
20
  import canonicalize from "canonicalize";
20
21
  import {
21
22
  GlobalOverviewFileName,
@@ -33,6 +34,7 @@ import { LRUCache } from "lru-cache";
33
34
  import * as semver from "semver";
34
35
  import { calculateSha256 } from "../../util";
35
36
  import { retry, Retry2TimesWithDelay } from "@milaboratories/ts-helpers";
37
+ import { util } from "@platforma-sdk/package-builder-lib";
36
38
 
37
39
  export type RegistryV2ReaderOps = {
38
40
  /** Number of milliseconds to cache retrieved block list for */
@@ -68,6 +70,34 @@ export function inferUpdateSuggestions(currentVersion: string, availableVersions
68
70
  return suggestions;
69
71
  }
70
72
 
73
+ /**
74
+ * A registry file could not be read for a reason other than its absence: the network, the
75
+ * server, or content that does not parse. The message carries the cause's text.
76
+ */
77
+ export class RegistryReadError extends Error {
78
+ name = "RegistryReadError";
79
+ }
80
+
81
+ function errorText(e: unknown): string {
82
+ return e instanceof Error ? e.message : String(e);
83
+ }
84
+
85
+ function isAbortError(e: unknown): boolean {
86
+ return e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError");
87
+ }
88
+
89
+ /** Whether a failed registry read is worth another try: not an absent file, not an abort. */
90
+ function isRetriableRead(e: unknown, signal: AbortSignal | undefined): boolean {
91
+ return !isFileNotFound(e) && !isAbortError(e) && signal?.aborted !== true;
92
+ }
93
+
94
+ /** `{org}/{name}/{version}/{fileName}` under `kinds/` for a kind reference `{name}@{version}`. */
95
+ function kindFilePath(ref: BlockKindReference, fileName: string): string {
96
+ const { name, version } = parseKindRef(ref);
97
+ const { org, name: kindName } = npmNameToKindPath(name);
98
+ return `${org}/${kindName}/${version}/${fileName}`;
99
+ }
100
+
71
101
  export class RegistryV2Reader {
72
102
  private readonly v2RootFolderReader: FolderReader;
73
103
  /** Rooted at `kinds/`, a sibling of `v2/` — the kind projection tree. */
@@ -247,7 +277,11 @@ export class RegistryV2Reader {
247
277
  }, Retry2TimesWithDelay);
248
278
  }
249
279
 
250
- private readonly componentsCache = new LRUCache<string, BlockComponentsAbsoluteUrl, BlockPackId>({
280
+ private readonly manifestCache = new LRUCache<
281
+ string,
282
+ { manifest: BlockPackManifest; components: BlockComponentsAbsoluteUrl },
283
+ BlockPackId
284
+ >({
251
285
  max: 500,
252
286
  fetchMethod: async (_key, _staleValue, { context: id }) =>
253
287
  await retry(async () => {
@@ -257,15 +291,21 @@ export class RegistryV2Reader {
257
291
  const manifest = BlockPackManifest.parse(
258
292
  JSON.parse(Buffer.from(await packageFolderReader.readFile(ManifestFileName)).toString()),
259
293
  );
260
- return blockComponentsManifestToAbsoluteUrl(
294
+ const components = blockComponentsManifestToAbsoluteUrl(
261
295
  manifest.description.components,
262
296
  packageFolderReader.rootUrl.toString(),
263
297
  );
298
+ return { manifest, components };
264
299
  }, Retry2TimesWithDelay),
265
300
  });
266
301
 
267
302
  public async getComponents(id: BlockPackId): Promise<BlockComponentsAbsoluteUrl> {
268
- return await this.componentsCache.forceFetch(canonicalize(id)!, { context: id });
303
+ return (await this.manifestCache.forceFetch(canonicalize(id)!, { context: id })).components;
304
+ }
305
+
306
+ /** The published manifest of a block version: file hashes and the pack-time meta. */
307
+ public async getManifest(id: BlockPackId): Promise<BlockPackManifest> {
308
+ return (await this.manifestCache.forceFetch(canonicalize(id)!, { context: id })).manifest;
269
309
  }
270
310
 
271
311
  /**
@@ -276,6 +316,9 @@ export class RegistryV2Reader {
276
316
  *
277
317
  * Client-side selector→version resolution is left to the §6 resolution
278
318
  * concern; this method only fetches and parses.
319
+ *
320
+ * @throws RegistryReadError when the overview is there but cannot be read or parsed, so an
321
+ * outage is not reported as a missing kind.
279
322
  */
280
323
  public async getKindOverview(
281
324
  kindNpmName: string,
@@ -283,19 +326,76 @@ export class RegistryV2Reader {
283
326
  ): Promise<KindOverview | undefined> {
284
327
  const { org, name } = npmNameToKindPath(kindNpmName);
285
328
  const relPath = `${org}/${name}/${KindOverviewFileName}`;
329
+ const signal = options?.signal;
286
330
  try {
287
- return await retry(async () => {
288
- const bytes = await this.kindsRootFolderReader.readFile(relPath, {
289
- signal: options?.signal,
290
- });
291
- return KindOverview.parse(JSON.parse(Buffer.from(bytes).toString()));
292
- }, Retry2TimesWithDelay);
293
- } catch {
294
- // Absent overview (or unreadable) → treat as "no such kind projection".
295
- return undefined;
331
+ // Only the read is retried: content that does not parse would not parse again.
332
+ const bytes = await retry(
333
+ async () => await this.kindsRootFolderReader.readFile(relPath, { signal }),
334
+ Retry2TimesWithDelay,
335
+ (e) => isRetriableRead(e, signal),
336
+ );
337
+ return KindOverview.parse(JSON.parse(Buffer.from(bytes).toString()));
338
+ } catch (e: unknown) {
339
+ if (isFileNotFound(e)) return undefined;
340
+ if (isAbortError(e) || signal?.aborted === true) throw e;
341
+ throw new RegistryReadError(
342
+ `Reading the overview of kind ${kindNpmName} from the registry failed: ${errorText(e)}`,
343
+ { cause: e },
344
+ );
296
345
  }
297
346
  }
298
347
 
348
+ /**
349
+ * Reads one file of a published kind version, `kinds/{org}/{name}/{version}/{fileName}`, such
350
+ * as `contract.d.ts`. Returns `undefined` when the version has no such file.
351
+ *
352
+ * @param ref an exact kind reference, `{name}@{version}`
353
+ * @throws RegistryReadError when the file cannot be read for another reason
354
+ */
355
+ public async readKindFile(
356
+ ref: BlockKindReference,
357
+ fileName: string,
358
+ options?: { signal?: AbortSignal },
359
+ ): Promise<Buffer | undefined> {
360
+ const path = kindFilePath(ref, fileName);
361
+ try {
362
+ return await retry(
363
+ async () => await this.kindsRootFolderReader.readFile(path, { signal: options?.signal }),
364
+ Retry2TimesWithDelay,
365
+ (e) => isRetriableRead(e, options?.signal),
366
+ );
367
+ } catch (e: unknown) {
368
+ if (isFileNotFound(e)) return undefined;
369
+ throw new RegistryReadError(`Reading ${path} from the registry failed: ${errorText(e)}`, {
370
+ cause: e,
371
+ });
372
+ }
373
+ }
374
+
375
+ /**
376
+ * The URL of one file of a published kind version, as {@link readKindFile} reads it, without
377
+ * credentials or query.
378
+ *
379
+ * @param ref an exact kind reference, `{name}@{version}`
380
+ */
381
+ public kindFileUrl(ref: BlockKindReference, fileName: string): string {
382
+ return util.redactUrl(new URL(kindFilePath(ref, fileName), this.kindsRootFolderReader.rootUrl));
383
+ }
384
+
385
+ /**
386
+ * The homepage a published block names in its meta (`url`), `undefined` when it names none.
387
+ * Reads the block's manifest on every call.
388
+ */
389
+ public async getBlockHomepage(id: BlockPackId): Promise<string | undefined> {
390
+ return await retry(async () => {
391
+ const manifestContent = await this.v2RootFolderReader.readFile(
392
+ packageContentPrefixInsideV2(id) + ManifestSuffix,
393
+ );
394
+ return BlockPackManifest.parse(JSON.parse(Buffer.from(manifestContent).toString()))
395
+ .description.meta.url;
396
+ }, Retry2TimesWithDelay);
397
+ }
398
+
299
399
  /**
300
400
  * Resolve a kind reference (`{name}@{selector}`) to a concrete implementing
301
401
  * block, returning the **byte-identical** `from-registry-v2` spec shape that
@@ -8,13 +8,26 @@ import { parsePackageName } from "../source_package";
8
8
  *
9
9
  * Layout mirrors the package tree one level down:
10
10
  * kinds/{org}/{name}/{version}/manifest.json — immutable kind content (publishKind)
11
- * kinds/{org}/{name}/{version}/kind.d.ts — kind artifacts
11
+ * kinds/{org}/{name}/{version}/contract.d.ts — kind artifacts (the files the manifest lists)
12
12
  * kinds/{org}/{name}/overview.json — projection over implementing blocks (reconciler)
13
13
  */
14
14
  export const KindsPrefix = "kinds/";
15
15
 
16
16
  export const KindOverviewFileName = "overview.json";
17
17
  export const KindManifestFileName = "manifest.json";
18
+ /**
19
+ * The declaration of a kind's params written for agents to read (`get_block_contract`): one file,
20
+ * the kind's own types written out, the SDK types they use imported by name. A kind version
21
+ * without it was built before; its declarations are only in {@link KindDeclarationFileName}.
22
+ * `@milaboratories/ts-builder build --target block-kind` writes it; `build-kind-manifest` requires it.
23
+ */
24
+ export const KindContractFileName = "contract.d.ts";
25
+
26
+ /**
27
+ * The declarations kind versions were published with before {@link KindContractFileName}: every
28
+ * dependency inlined, tens of KB. Readers only point to it.
29
+ */
30
+ export const KindDeclarationFileName = "kind.d.ts";
18
31
 
19
32
  /** Location of a kind inside the `kinds/` tree, split into path segments. */
20
33
  export interface KindPathLocation {