@eum-agent/extension-catalog 1.0.0 → 1.0.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 (2) hide show
  1. package/dist/index.js +59 -78
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -180,7 +180,6 @@ const CatalogSchema = z.object({ releases: z.array(ReleaseSchema).max(2e3) }).st
180
180
  const SnapshotSchema = z.object({
181
181
  repository: z.literal(CATALOG_REPOSITORY),
182
182
  commit: GitShaSchema,
183
- treeSha: GitShaSchema,
184
183
  contentDigest: z.string().regex(/^[0-9a-f]{64}$/),
185
184
  fetchedAt: z.iso.datetime({ offset: true }),
186
185
  revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
@@ -380,6 +379,7 @@ function createDefaultsService(options) {
380
379
  record.lastReasonCode = "INSTALL_FAILED";
381
380
  }
382
381
  }
382
+ if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
383
383
  persist(record);
384
384
  }
385
385
  async function joinOperation(operationId) {
@@ -447,7 +447,7 @@ function createDefaultsService(options) {
447
447
  }
448
448
  if (record.state === "complete") return;
449
449
  const observations = await options.installer.observe();
450
- for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName)) {
450
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
451
451
  candidate.state = "user-managed";
452
452
  candidate.reasonCode = "USER_DECLARATION_PRESERVED";
453
453
  } else {
@@ -543,7 +543,6 @@ function createDefaultsService(options) {
543
543
  const AcceptedSnapshotSchema = z.object({
544
544
  repository: z.literal(CATALOG_REPOSITORY),
545
545
  commit: GitShaSchema,
546
- treeSha: GitShaSchema,
547
546
  contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
548
547
  }).strict();
549
548
  z.object({
@@ -595,24 +594,49 @@ function projectInstalled(observations, snapshot, host) {
595
594
  }
596
595
  //#endregion
597
596
  //#region src/extension-catalog/sync.ts
598
- const api = "https://api.github.com/repos/yanxuan-lc/yaoguang-presets";
599
- const commitSchema = z.object({
600
- sha: GitShaSchema,
601
- commit: z.object({ tree: z.object({ sha: GitShaSchema }) })
602
- });
603
- const treeSchema = z.object({
604
- sha: GitShaSchema,
605
- truncated: z.literal(false),
606
- tree: z.array(z.object({
607
- path: z.string().max(4096),
608
- mode: z.string(),
609
- type: z.string(),
610
- sha: GitShaSchema
611
- })).max(2e4)
612
- });
613
- const blobSha = (bytes) => createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
614
- /** Reads a bounded response without credentials, redirects, or remote-body diagnostics. */
615
- async function readBoundedResponse(network, url, signal, maxBytes, headers = {}) {
597
+ /** Git smart HTTP ref advertisement for the catalog repository. */
598
+ const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
599
+ /** Raw content URL of the extension index pinned to one commit. */
600
+ const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
601
+ const REFS_MAX_BYTES = 1048576;
602
+ const headers = { "User-Agent": "YaoGuang-extensions" };
603
+ /**
604
+ * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
605
+ * Requires the leading service announcement and well-formed pkt-lines; any other shape,
606
+ * including a missing main branch, is rejected as an invalid catalog.
607
+ */
608
+ function parseMainCommit(bytes) {
609
+ const text = Buffer.from(bytes).toString("latin1");
610
+ const lines = [];
611
+ for (let at = 0; at < text.length;) {
612
+ const prefix = text.slice(at, at + 4);
613
+ if (!/^[0-9a-f]{4}$/.test(prefix)) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
614
+ const length = Number.parseInt(prefix, 16);
615
+ if (length === 0) {
616
+ lines.push(null);
617
+ at += 4;
618
+ continue;
619
+ }
620
+ if (length < 4 || at + length > text.length) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
621
+ lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
622
+ at += length;
623
+ }
624
+ if (lines[0] !== "# service=git-upload-pack" || lines[1] !== null) throw new CatalogError("CATALOG_INVALID", "Missing upload-pack service announcement");
625
+ for (const line of lines.slice(2)) {
626
+ if (line === null) continue;
627
+ const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
628
+ if (!match) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
629
+ if (match[2] === "refs/heads/main") return match[1];
630
+ }
631
+ throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
632
+ }
633
+ /**
634
+ * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
635
+ * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
636
+ * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
637
+ * A 404 throws the error built by `notFound` when it is supplied.
638
+ */
639
+ async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
616
640
  signal.throwIfAborted();
617
641
  const response = await network.fetch(url, {
618
642
  signal,
@@ -621,7 +645,9 @@ async function readBoundedResponse(network, url, signal, maxBytes, headers = {})
621
645
  });
622
646
  if (!response.ok) {
623
647
  await response.body?.cancel().catch(() => {});
624
- const retry = Number(response.headers.get("retry-after"));
648
+ if (response.status === 404 && notFound) throw notFound();
649
+ let retry = Number(response.headers.get("retry-after"));
650
+ if (!(Number.isFinite(retry) && retry > 0) && (response.status === 429 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0")) retry = Number(response.headers.get("x-ratelimit-reset")) - Math.floor(Date.now() / 1e3);
625
651
  throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
626
652
  }
627
653
  if (Number(response.headers.get("content-length")) > maxBytes) {
@@ -648,69 +674,25 @@ async function readBoundedResponse(network, url, signal, maxBytes, headers = {})
648
674
  reader.releaseLock();
649
675
  }
650
676
  }
651
- /** Fetches and verifies a whole index and all release files pinned to one Git tree. */
677
+ /**
678
+ * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
679
+ * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
680
+ * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
681
+ */
652
682
  async function synchronize(network, ownerSignal, previous) {
653
683
  const controller = new AbortController();
654
684
  const signal = AbortSignal.any([ownerSignal, controller.signal]);
655
685
  const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
656
- let remaining = CATALOG_MAX_BYTES;
657
- async function read(path, raw = false) {
658
- const bytes = await readBoundedResponse(network, `${api}/${path}`, signal, remaining, {
659
- Accept: raw ? "application/vnd.github.raw+json" : "application/vnd.github+json",
660
- "X-GitHub-Api-Version": "2026-03-10",
661
- "User-Agent": "YaoGuang-extensions"
662
- });
663
- remaining -= bytes.length;
664
- if (remaining < 0) throw new CatalogError("LIMIT_EXCEEDED", "Whole catalog exceeds 8 MiB");
665
- return bytes;
666
- }
667
686
  try {
668
- const commit = commitSchema.parse(parseJson(decodeUtf8(await read("commits/main"))));
669
- if (previous?.commit === commit.sha && previous.treeSha === commit.commit.tree.sha) return {
687
+ const commit = parseMainCommit(await readBoundedResponse(network, CATALOG_REFS_URL, signal, REFS_MAX_BYTES, headers));
688
+ if (previous?.commit === commit) return {
670
689
  ...previous,
671
690
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
672
691
  };
673
- const tree = treeSchema.parse(parseJson(decodeUtf8(await read(`git/trees/${commit.commit.tree.sha}?recursive=1`))));
674
- if (tree.sha !== commit.commit.tree.sha) throw new CatalogError("CATALOG_INVALID", "Commit tree mismatch");
675
- const paths = /* @__PURE__ */ new Set();
676
- for (const item of tree.tree) {
677
- if (paths.has(item.path)) throw new CatalogError("CATALOG_INVALID", "Duplicate tree path");
678
- paths.add(item.path);
679
- if (item.path === "extensions" || item.path.startsWith("extensions/")) {
680
- if (item.path.split("/").some((p) => !p || p === "." || p === "..") || item.path.includes("\\") || !(item.mode === "100644" && item.type === "blob" || item.mode === "040000" && item.type === "tree")) throw new CatalogError("CATALOG_INVALID", "Catalog contains unsafe tree entry");
681
- }
682
- }
683
- const index = tree.tree.find((item) => item.path === "extensions/index.json");
684
- if (!index || index.mode !== "100644") throw new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available");
685
- const bytes = await read(`git/blobs/${index.sha}`, true);
686
- if (blobSha(bytes) !== index.sha) throw new CatalogError("CATALOG_INVALID", "Index Git blob digest mismatch");
687
- const releases = decodeReleases(parseJson(decodeUtf8(bytes)));
688
- const files = tree.tree.filter((item) => item.type === "blob" && item.path.startsWith("extensions/releases/"));
689
- if (files.length !== releases.length || files.some((item) => !/^extensions\/releases\/[^/]+\.json$/.test(item.path))) throw new CatalogError("CATALOG_INVALID", "Release file coverage mismatch");
690
- let next = 0;
691
- const records = /* @__PURE__ */ new Map();
692
- const failed = (await Promise.allSettled(Array.from({ length: Math.min(4, files.length) }, async () => {
693
- try {
694
- for (;;) {
695
- const item = files[next++];
696
- if (!item) return;
697
- const content = await read(`git/blobs/${item.sha}`, true);
698
- if (blobSha(content) !== item.sha) throw new CatalogError("CATALOG_INVALID", "Release Git blob digest mismatch");
699
- const release = ReleaseSchema.parse(parseJson(decodeUtf8(content)));
700
- if (records.has(release.releaseId)) throw new CatalogError("CATALOG_INVALID", "Duplicate release file");
701
- records.set(release.releaseId, recordDigest(release));
702
- }
703
- } catch (error) {
704
- controller.abort(error);
705
- throw error;
706
- }
707
- }))).find((result) => result.status === "rejected");
708
- if (failed?.status === "rejected") throw failed.reason;
709
- if (releases.some((release) => records.get(release.releaseId) !== recordDigest(release))) throw new CatalogError("CATALOG_INVALID", "Index and release contents differ");
692
+ const releases = decodeReleases(parseJson(decodeUtf8(await readBoundedResponse(network, catalogIndexUrl(commit), signal, CATALOG_MAX_BYTES, headers, () => new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available")))));
710
693
  return {
711
694
  repository: CATALOG_REPOSITORY,
712
- commit: commit.sha,
713
- treeSha: tree.sha,
695
+ commit,
714
696
  contentDigest: recordDigest({ releases }),
715
697
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
716
698
  revision: previous?.revision ?? 0,
@@ -852,7 +834,7 @@ function createCatalogService(options) {
852
834
  if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
853
835
  if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
854
836
  const existing = observations.find((o) => o.packageName === release.packageName);
855
- if (automatic && existing) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
837
+ if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
856
838
  if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
857
839
  const prior = roots.find((r) => r.packageName === release.packageName);
858
840
  if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
@@ -882,7 +864,7 @@ function createCatalogService(options) {
882
864
  if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
883
865
  continue;
884
866
  }
885
- const installed = observations.find((o) => o.packageName === name);
867
+ const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
886
868
  if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
887
869
  const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
888
870
  if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
@@ -902,7 +884,6 @@ function createCatalogService(options) {
902
884
  snapshot: {
903
885
  repository: accepted.repository,
904
886
  commit: accepted.commit,
905
- treeSha: accepted.treeSha,
906
887
  contentDigest: accepted.contentDigest
907
888
  },
908
889
  release: candidate,
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "en-US": "Extension Catalog",
5
5
  "zh-CN": "扩展目录"
6
6
  },
7
- "version": "1.0.0",
7
+ "version": "1.0.2",
8
8
  "type": "module",
9
9
  "description": "Extension Catalog",
10
10
  "license": "MIT",