fluncle 0.283.0 → 0.284.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.
Files changed (2) hide show
  1. package/bin/fluncle.mjs +883 -13
  2. package/package.json +1 -1
package/bin/fluncle.mjs CHANGED
@@ -704,7 +704,7 @@ function parseVersion(version) {
704
704
  var currentVersion;
705
705
  var init_version = __esm(() => {
706
706
  init_output();
707
- currentVersion = "0.283.0".trim() ? "0.283.0".trim() : "0.1.0";
707
+ currentVersion = "0.284.0".trim() ? "0.284.0".trim() : "0.1.0";
708
708
  });
709
709
 
710
710
  // src/update-notifier.ts
@@ -11145,7 +11145,7 @@ function parseVersion2(version) {
11145
11145
  var currentVersion2, latestReleaseUrl = "https://api.github.com/repos/mauricekleine/fluncle/releases/latest";
11146
11146
  var init_version2 = __esm(() => {
11147
11147
  init_output();
11148
- currentVersion2 = "0.283.0".trim() ? "0.283.0".trim() : "0.1.0";
11148
+ currentVersion2 = "0.284.0".trim() ? "0.284.0".trim() : "0.1.0";
11149
11149
  });
11150
11150
 
11151
11151
  // ../../packages/registry/src/index.ts
@@ -14159,6 +14159,18 @@ function prefixIssues(path, issues) {
14159
14159
  function unwrapMessage(message) {
14160
14160
  return typeof message === "string" ? message : message?.message;
14161
14161
  }
14162
+ function sizeCaps(defChecks) {
14163
+ const caps = [];
14164
+ for (const ch of defChecks ?? []) {
14165
+ const d = ch._zod.def;
14166
+ if (!/_(length|size)$|_equals$/.test(d.check))
14167
+ break;
14168
+ const max = d.maximum ?? d.length ?? d.size;
14169
+ if (max >= 0)
14170
+ caps.push([max, ch]);
14171
+ }
14172
+ return caps;
14173
+ }
14162
14174
  function attachSchema(issues, start, inst) {
14163
14175
  var _a;
14164
14176
  for (let i = start;i < issues.length; i++) {
@@ -15204,7 +15216,7 @@ var init_versions = __esm(() => {
15204
15216
  version = {
15205
15217
  major: 4,
15206
15218
  minor: 6,
15207
- patch: 5
15219
+ patch: 7
15208
15220
  };
15209
15221
  });
15210
15222
 
@@ -15330,6 +15342,28 @@ function isValidJWT(token, algorithm = null) {
15330
15342
  return false;
15331
15343
  }
15332
15344
  }
15345
+ function capSize(inst, size) {
15346
+ const caps = sizeCaps(inst._zod.def.checks);
15347
+ if (!caps.length)
15348
+ return;
15349
+ const cap = Math.min(...caps.map((c) => c[0]));
15350
+ const parse = inst._zod.parse;
15351
+ inst._zod.parse = (payload, ctx) => {
15352
+ const n = size(payload.value);
15353
+ if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
15354
+ for (const [max, ch] of sizeCaps(inst._zod.def.checks)) {
15355
+ if (n > max && ch._zod.def.when(payload)) {
15356
+ const start = payload.issues.length;
15357
+ ch._zod.check(payload);
15358
+ payload.issues[start].continue = false;
15359
+ attachSchema(payload.issues, start, inst);
15360
+ return payload;
15361
+ }
15362
+ }
15363
+ }
15364
+ return parse(payload, ctx);
15365
+ };
15366
+ }
15333
15367
  function handleArrayResult(result, final, index) {
15334
15368
  if (result.issues.length) {
15335
15369
  final.issues.push(...prefixIssues(index, result.issues));
@@ -15721,7 +15755,7 @@ function handleRefineResult(result, payload, input, inst) {
15721
15755
  payload.issues.push(issue(_iss));
15722
15756
  }
15723
15757
  }
15724
- var $ZodType, toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config3())) } : { value: r.value }, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT = 1, URL_UNPARSEABLE = 2, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodNull, $ZodUnknown, $ZodNever, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodLazy, $ZodCustom;
15758
+ var $ZodType, toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config3())) } : { value: r.value }, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT = 1, URL_UNPARSEABLE = 2, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodNull, $ZodUnknown, $ZodNever, arraySize = (input) => Array.isArray(input) ? input.length : -1, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodLazy, $ZodCustom;
15725
15759
  var init_schemas = __esm(() => {
15726
15760
  init_checks();
15727
15761
  init_core2();
@@ -16207,6 +16241,7 @@ var init_schemas = __esm(() => {
16207
16241
  }
16208
16242
  return payload;
16209
16243
  };
16244
+ capSize(inst, arraySize);
16210
16245
  });
16211
16246
  NO_SYMBOL_KEYS = [];
16212
16247
  $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
@@ -31453,6 +31488,7 @@ async function resolveTarget(input, deps) {
31453
31488
  };
31454
31489
  }
31455
31490
  async function gatherLabelEvidence(input, options, deps) {
31491
+ const before = { cacheHits: deps.http.stats.cacheHits, network: deps.http.stats.requests };
31456
31492
  const label = await resolveTarget(input, deps);
31457
31493
  const wants = (source) => options.sources.includes(source);
31458
31494
  const needsMb = wants("musicbrainz") || wants("discogs") || wants("beatport") || wants("apple");
@@ -31474,7 +31510,10 @@ async function gatherLabelEvidence(input, options, deps) {
31474
31510
  label: { ...label, name: label.name ?? mb.label?.name },
31475
31511
  ok: answered.length > 0,
31476
31512
  partial: answered.length < requested.length || errors.length > 0,
31477
- requests: { cacheHits: deps.http.stats.cacheHits, network: deps.http.stats.requests },
31513
+ requests: {
31514
+ cacheHits: deps.http.stats.cacheHits - before.cacheHits,
31515
+ network: deps.http.stats.requests - before.network
31516
+ },
31478
31517
  sources
31479
31518
  };
31480
31519
  }
@@ -31529,17 +31568,17 @@ function defaultBeatportScraper(env, http) {
31529
31568
  }
31530
31569
  return env.firecrawlBinary ? firecrawlCliScraper(env.firecrawlBinary) : null;
31531
31570
  }
31532
- async function labelEvidenceCommand(input, options) {
31571
+ async function createLabelEvidenceDeps(refresh) {
31533
31572
  const [{ readOptionalEnv }, { resolveLabel }] = await Promise.all([
31534
31573
  Promise.resolve().then(() => (init_env(), exports_env)),
31535
31574
  Promise.resolve().then(() => (init_admin_labels3(), exports_admin_labels))
31536
31575
  ]);
31537
- const http = createEvidenceHttp({ deadline: deadlineAt(), refresh: options.refresh });
31576
+ const http = createEvidenceHttp({ deadline: deadlineAt(), refresh });
31538
31577
  const discogsToken = readOptionalEnv("DISCOGS_USER_TOKEN");
31539
31578
  if (discogsToken) {
31540
31579
  http.policies = { ...http.policies, discogs: { ...http.policies.discogs, intervalMs: 1100 } };
31541
31580
  }
31542
- return gatherLabelEvidence(input, options, {
31581
+ return {
31543
31582
  discogsToken,
31544
31583
  http,
31545
31584
  resolveLabel,
@@ -31547,11 +31586,27 @@ async function labelEvidenceCommand(input, options) {
31547
31586
  firecrawlApiKey: readOptionalEnv("FIRECRAWL_API_KEY"),
31548
31587
  firecrawlBinary: Bun.which("firecrawl")
31549
31588
  }, http)
31550
- });
31589
+ };
31590
+ }
31591
+ async function labelEvidenceCommand(input, options) {
31592
+ return gatherLabelEvidence(input, options, await createLabelEvidenceDeps(options.refresh));
31551
31593
  }
31552
31594
  function countLine(counts, limit) {
31553
31595
  return counts.slice(0, limit).map((entry) => `${entry.name} ${entry.count}`).join(", ");
31554
31596
  }
31597
+ function musicbrainzDetailLines(mb) {
31598
+ const lines = [];
31599
+ if (mb?.label?.labelRelations.length) {
31600
+ lines.push(` label relations: ${mb.label.labelRelations.map((relation) => `${relation.type}: ${relation.name} (${relation.mbid})`).join("; ")}`);
31601
+ }
31602
+ if (mb?.census) {
31603
+ lines.push(` first credits: ${mb.census.firstCredits.map((credit) => `${credit.artistName} (${credit.artistMbid}) ${credit.recordings}`).join("; ")}; uncredited ${mb.census.uncreditedRecordings}`);
31604
+ }
31605
+ for (const release of mb?.releases?.releases ?? []) {
31606
+ lines.push(` release: ${release.artist} — ${release.title}; catno ${release.catno ?? "none"}; ${release.date ?? "undated"}`);
31607
+ }
31608
+ return lines;
31609
+ }
31555
31610
  function labelEvidenceLines(evidence) {
31556
31611
  const { apple, beatport, discogs, musicbrainz } = evidence.sources;
31557
31612
  const mb = musicbrainz.data;
@@ -31562,13 +31617,14 @@ function labelEvidenceLines(evidence) {
31562
31617
  mbParts.push([mb.label.type, mb.label.area, mb.label.lifeSpan.begin].filter(Boolean).join(", "));
31563
31618
  }
31564
31619
  if (mb?.releases) {
31565
- const top = mb.releases.firstCreditArtists.slice(0, 6).map((artist) => `${artist.name} ${artist.releases}`).join(", ");
31620
+ const top = mb.releases.firstCreditArtists.slice(0, FIRST_CREDIT_ARTISTS).map((artist) => `${artist.name} ${artist.releases}`).join(", ");
31566
31621
  mbParts.push(`${mb.releases.releaseCount} releases; first credits: ${top || "none"}`);
31567
31622
  }
31568
31623
  if (mb?.census) {
31569
31624
  mbParts.push(`census ${mb.census.recordingsCounted} recordings over ${mb.census.releasesRead} releases${mb.census.caveat ? ` (${mb.census.caveat})` : ""}`);
31570
31625
  }
31571
31626
  lines.push(` musicbrainz: ${musicbrainz.status}${mbParts.length ? ` — ${mbParts.join("; ")}` : ""}`);
31627
+ lines.push(...musicbrainzDetailLines(mb));
31572
31628
  const dg = discogs.data;
31573
31629
  const dgDetail = dg?.styles ? `styles: ${countLine(dg.styles.styles, 6)} (${dg.styles.releasesRead} releases)` : dg?.candidates ? `unverified candidates: ${dg.candidates.map((c) => c.title).join(", ") || "none"}` : discogs.note;
31574
31630
  lines.push(` discogs: ${discogs.status}${dgDetail ? ` — ${dgDetail}` : ""}`);
@@ -31591,6 +31647,797 @@ var init_admin_label_evidence = __esm(() => {
31591
31647
  EVIDENCE_SOURCES = ["musicbrainz", "discogs", "beatport", "apple"];
31592
31648
  });
31593
31649
 
31650
+ // src/commands/admin-label-evidence.ts
31651
+ import { spawn as spawn2 } from "node:child_process";
31652
+ function failureOf2(error, request) {
31653
+ if (error instanceof EvidenceFetchError) {
31654
+ return {
31655
+ attempts: error.attempts,
31656
+ kind: error.kind,
31657
+ message: error.message,
31658
+ request,
31659
+ ...error.status === undefined ? {} : { status: error.status }
31660
+ };
31661
+ }
31662
+ return {
31663
+ kind: "parse",
31664
+ message: error instanceof Error ? error.message : String(error),
31665
+ request
31666
+ };
31667
+ }
31668
+ function statusFrom2(parts, failures) {
31669
+ if (failures === 0) {
31670
+ return "ok";
31671
+ }
31672
+ return failures < parts ? "partial" : "error";
31673
+ }
31674
+ function tally2(names) {
31675
+ const counts = new Map;
31676
+ for (const name of names) {
31677
+ counts.set(name, (counts.get(name) ?? 0) + 1);
31678
+ }
31679
+ return [...counts.entries()].map(([name, count]) => ({ count, name })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
31680
+ }
31681
+ function firstCredit2(credit) {
31682
+ const head = credit?.[0];
31683
+ const mbid = head?.artist?.id;
31684
+ if (!mbid) {
31685
+ return null;
31686
+ }
31687
+ return { mbid, name: head?.artist?.name ?? head?.name ?? mbid };
31688
+ }
31689
+ function crawlRuleCredit2(credit) {
31690
+ for (const entry of credit ?? []) {
31691
+ const name = entry.artist?.name ?? entry.name;
31692
+ const mbid = entry.artist?.id;
31693
+ if (name && mbid && mbid !== VARIOUS_ARTISTS_MBID2) {
31694
+ return { mbid, name };
31695
+ }
31696
+ }
31697
+ return null;
31698
+ }
31699
+ function creditString2(credit) {
31700
+ return (credit ?? []).map((entry) => entry.name ?? entry.artist?.name ?? "").join(" / ");
31701
+ }
31702
+ function linkOf2(links, host) {
31703
+ return links.find((link) => link.url.includes(host))?.url ?? null;
31704
+ }
31705
+ function toLabelFacts2(payload, mbid) {
31706
+ const relations = payload.relations ?? [];
31707
+ return {
31708
+ area: payload.area?.name ?? null,
31709
+ country: payload.country ?? null,
31710
+ disambiguation: payload.disambiguation || null,
31711
+ genres: (payload.genres ?? []).flatMap((genre) => genre.name ? [genre.name] : []),
31712
+ labelCode: payload["label-code"] ?? null,
31713
+ labelRelations: relations.flatMap((relation) => relation.label?.id ? [
31714
+ {
31715
+ direction: relation.direction ?? "forward",
31716
+ mbid: relation.label.id,
31717
+ name: relation.label.name ?? relation.label.id,
31718
+ type: relation.type ?? "unknown"
31719
+ }
31720
+ ] : []),
31721
+ lifeSpan: {
31722
+ begin: payload["life-span"]?.begin ?? null,
31723
+ end: payload["life-span"]?.end ?? null,
31724
+ ended: payload["life-span"]?.ended === true
31725
+ },
31726
+ links: relations.flatMap((relation) => relation.url?.resource ? [{ type: relation.type ?? "unknown", url: relation.url.resource }] : []),
31727
+ mbid: payload.id ?? mbid,
31728
+ name: payload.name ?? mbid,
31729
+ tags: (payload.tags ?? []).flatMap((tag) => tag.name ? [tag.name] : []),
31730
+ type: payload.type ?? null
31731
+ };
31732
+ }
31733
+ function toReleaseFacts2(browse, mbid) {
31734
+ const releases = browse.releases ?? [];
31735
+ const byArtist = new Map;
31736
+ let variousArtistsReleases = 0;
31737
+ const samples = releases.map((release) => {
31738
+ const head = firstCredit2(release["artist-credit"]);
31739
+ if (head?.mbid === VARIOUS_ARTISTS_MBID2) {
31740
+ variousArtistsReleases += 1;
31741
+ } else if (head) {
31742
+ const entry = byArtist.get(head.mbid) ?? { mbid: head.mbid, name: head.name, releases: 0 };
31743
+ entry.releases += 1;
31744
+ byArtist.set(head.mbid, entry);
31745
+ }
31746
+ const info = release["label-info"]?.find((entry) => entry.label?.id === mbid);
31747
+ const formats = [
31748
+ ...new Set((release.media ?? []).flatMap((m) => m.format ? [m.format] : []))
31749
+ ];
31750
+ return {
31751
+ artist: creditString2(release["artist-credit"]),
31752
+ barcode: release.barcode || null,
31753
+ catno: info?.["catalog-number"] ?? null,
31754
+ date: release.date || null,
31755
+ format: formats.length > 0 ? formats.join(" + ") : null,
31756
+ mbid: release.id,
31757
+ status: release.status ?? null,
31758
+ title: release.title ?? ""
31759
+ };
31760
+ });
31761
+ return {
31762
+ firstCreditArtists: [...byArtist.values()].sort((a, b) => b.releases - a.releases || a.name.localeCompare(b.name)).slice(0, FIRST_CREDIT_ARTISTS2),
31763
+ releaseCount: browse["release-count"] ?? releases.length,
31764
+ releases: samples.sort((a, b) => (b.date ?? "").localeCompare(a.date ?? "")).slice(0, RELEASE_SAMPLE2),
31765
+ releasesRead: releases.length,
31766
+ variousArtistsReleases
31767
+ };
31768
+ }
31769
+ async function runCensus2(deps, mbid, maxPages) {
31770
+ const credits = new Map;
31771
+ const seen = new Set;
31772
+ let offset = 0;
31773
+ let pagesFetched = 0;
31774
+ let releaseCount = 0;
31775
+ let allCached = true;
31776
+ let failure;
31777
+ let uncredited = 0;
31778
+ while (pagesFetched < maxPages) {
31779
+ const url = `${MB_ROOT2}/release?label=${mbid}&inc=artist-credits+recordings&limit=100&offset=${offset}&fmt=json`;
31780
+ let page;
31781
+ try {
31782
+ page = await fetchEvidenceJson(deps.http, "musicbrainz", url);
31783
+ } catch (error) {
31784
+ if (pagesFetched === 0) {
31785
+ throw error;
31786
+ }
31787
+ failure = failureOf2(error, url);
31788
+ break;
31789
+ }
31790
+ const { cached, data } = page;
31791
+ const releases = data.releases ?? [];
31792
+ allCached &&= cached;
31793
+ pagesFetched += 1;
31794
+ releaseCount = data["release-count"] ?? releaseCount;
31795
+ for (const release of releases) {
31796
+ for (const medium of release.media ?? []) {
31797
+ for (const track of medium.tracks ?? []) {
31798
+ const recordingId = track.recording?.id;
31799
+ if (!recordingId || seen.has(recordingId)) {
31800
+ continue;
31801
+ }
31802
+ seen.add(recordingId);
31803
+ const head = crawlRuleCredit2(track.recording?.["artist-credit"] ?? release["artist-credit"]);
31804
+ if (!head) {
31805
+ uncredited += 1;
31806
+ continue;
31807
+ }
31808
+ const entry = credits.get(head.mbid) ?? {
31809
+ artistMbid: head.mbid,
31810
+ artistName: head.name,
31811
+ recordings: 0
31812
+ };
31813
+ entry.recordings += 1;
31814
+ credits.set(head.mbid, entry);
31815
+ }
31816
+ }
31817
+ }
31818
+ offset += releases.length;
31819
+ if (releases.length === 0 || offset >= releaseCount) {
31820
+ break;
31821
+ }
31822
+ }
31823
+ const sampled = offset < releaseCount;
31824
+ const firstCredits = [...credits.values()].sort((a, b) => b.recordings - a.recordings || a.artistName.localeCompare(b.artistName));
31825
+ return {
31826
+ cached: allCached,
31827
+ ...failure ? { failure } : {},
31828
+ census: {
31829
+ caveat: sampled ? `sampled: first ${offset} of ${releaseCount} releases${failure ? " (a later page failed)" : ""}` : null,
31830
+ firstCredits,
31831
+ pagesFetched,
31832
+ recordingsCounted: firstCredits.reduce((sum, entry) => sum + entry.recordings, uncredited),
31833
+ releaseCount,
31834
+ releasesRead: offset,
31835
+ sampled,
31836
+ uncreditedRecordings: uncredited
31837
+ }
31838
+ };
31839
+ }
31840
+ async function gatherMusicBrainz2(deps, mbid, options) {
31841
+ const data = {};
31842
+ const errors = [];
31843
+ let parts = 2;
31844
+ let allCached = true;
31845
+ const labelUrl = `${MB_ROOT2}/label/${mbid}?inc=aliases+label-rels+url-rels+tags+genres&fmt=json`;
31846
+ try {
31847
+ const { cached, data: payload } = await fetchEvidenceJson(deps.http, "musicbrainz", labelUrl);
31848
+ allCached &&= cached;
31849
+ data.label = toLabelFacts2(payload, mbid);
31850
+ } catch (error) {
31851
+ errors.push(failureOf2(error, labelUrl));
31852
+ }
31853
+ const releasesUrl = `${MB_ROOT2}/release?label=${mbid}&inc=artist-credits+labels+media&limit=100&fmt=json`;
31854
+ try {
31855
+ const { cached, data: browse } = await fetchEvidenceJson(deps.http, "musicbrainz", releasesUrl);
31856
+ allCached &&= cached;
31857
+ data.releases = toReleaseFacts2(browse, mbid);
31858
+ } catch (error) {
31859
+ errors.push(failureOf2(error, releasesUrl));
31860
+ }
31861
+ if (options.census) {
31862
+ parts += 1;
31863
+ try {
31864
+ const { cached, census, failure } = await runCensus2(deps, mbid, options.censusPages);
31865
+ allCached &&= cached;
31866
+ data.census = census;
31867
+ if (failure) {
31868
+ errors.push(failure);
31869
+ }
31870
+ } catch (error) {
31871
+ errors.push(failureOf2(error, `${MB_ROOT2}/release?label=${mbid}&inc=recordings (census)`));
31872
+ }
31873
+ }
31874
+ return {
31875
+ cached: allCached,
31876
+ data,
31877
+ ...errors.length > 0 ? { errors } : {},
31878
+ status: statusFrom2(parts, errors.length)
31879
+ };
31880
+ }
31881
+ function discogsLabelIdFrom2(url) {
31882
+ const match = url ? /discogs\.com\/(?:[a-z]{2}\/)?label\/(\d+)/i.exec(url) : null;
31883
+ return match?.[1] ? Number(match[1]) : null;
31884
+ }
31885
+ function beatportLabelUrlFrom2(url) {
31886
+ const match = url ? /beatport\.com\/label\/([^/?#]+)\/(\d+)/i.exec(url) : null;
31887
+ return match?.[1] && match[2] ? `https://www.beatport.com/label/${match[1]}/${match[2]}` : null;
31888
+ }
31889
+ function discogsHeaders2(deps) {
31890
+ return deps.discogsToken ? { Authorization: `Discogs token=${deps.discogsToken}` } : {};
31891
+ }
31892
+ async function discogsCandidates2(deps, name) {
31893
+ const searchUrl = `${DISCOGS_ROOT2}/database/search?type=label&q=${encodeURIComponent(name)}&per_page=5`;
31894
+ try {
31895
+ const { cached, data } = await fetchEvidenceJson(deps.http, "discogs", searchUrl, discogsHeaders2(deps));
31896
+ const candidates = (data.results ?? []).flatMap((result) => result.id ? [
31897
+ {
31898
+ id: result.id,
31899
+ title: result.title ?? "",
31900
+ url: `https://www.discogs.com${result.uri ?? `/label/${result.id}`}`
31901
+ }
31902
+ ] : []);
31903
+ return {
31904
+ cached,
31905
+ data: { candidates },
31906
+ note: "The MusicBrainz label has no Discogs link. Candidates are unverified name matches: confirm the identity before citing any of them.",
31907
+ status: "no_link"
31908
+ };
31909
+ } catch (error) {
31910
+ return {
31911
+ errors: [failureOf2(error, searchUrl)],
31912
+ note: "The MusicBrainz label has no Discogs link.",
31913
+ status: "no_link"
31914
+ };
31915
+ }
31916
+ }
31917
+ function toDiscogsLabel2(payload, labelId, fallbackName) {
31918
+ const sublabels = (payload.sublabels ?? []).flatMap((entry) => entry.name ? [entry.name] : []);
31919
+ const parent = payload.parent_label;
31920
+ return {
31921
+ id: payload.id ?? labelId,
31922
+ name: payload.name ?? fallbackName,
31923
+ parentLabel: parent?.id === undefined ? null : { id: parent.id, name: parent.name ?? "" },
31924
+ profile: (payload.profile ?? "").slice(0, PROFILE_CHARS2),
31925
+ sublabelCount: sublabels.length,
31926
+ sublabels: sublabels.slice(0, 30),
31927
+ url: payload.uri ?? `https://www.discogs.com/label/${labelId}`,
31928
+ urls: payload.urls ?? []
31929
+ };
31930
+ }
31931
+ function toDiscogsReleases2(payload) {
31932
+ const releases = payload.releases ?? [];
31933
+ const ids = releases.flatMap((release) => {
31934
+ const id = release.type === "master" ? release.main_release : release.id;
31935
+ return typeof id === "number" ? [id] : [];
31936
+ });
31937
+ return {
31938
+ facts: {
31939
+ releaseCount: payload.pagination?.items ?? releases.length,
31940
+ sample: releases.slice(0, DISCOGS_RELEASE_SAMPLE2).map((release) => ({
31941
+ artist: release.artist ?? "",
31942
+ catno: release.catno ?? null,
31943
+ format: release.format ?? null,
31944
+ title: release.title ?? "",
31945
+ year: release.year || null
31946
+ })),
31947
+ topArtists: tally2(releases.map((release) => release.artist ?? "")).filter((entry) => entry.name !== "").slice(0, 15).map((entry) => ({ name: entry.name, releases: entry.count }))
31948
+ },
31949
+ ids
31950
+ };
31951
+ }
31952
+ async function gatherDiscogs2(deps, mb) {
31953
+ const labelFacts = mb.label;
31954
+ if (!labelFacts) {
31955
+ return {
31956
+ note: "MusicBrainz label unavailable, so no Discogs link to follow",
31957
+ status: "skipped"
31958
+ };
31959
+ }
31960
+ const labelId = discogsLabelIdFrom2(linkOf2(labelFacts.links, "discogs.com"));
31961
+ if (labelId === null) {
31962
+ return discogsCandidates2(deps, labelFacts.name);
31963
+ }
31964
+ const headers = discogsHeaders2(deps);
31965
+ const data = {};
31966
+ const errors = [];
31967
+ const releaseIds = new Set;
31968
+ let allCached = true;
31969
+ const labelUrl = `${DISCOGS_ROOT2}/labels/${labelId}`;
31970
+ try {
31971
+ const { cached, data: payload } = await fetchEvidenceJson(deps.http, "discogs", labelUrl, headers);
31972
+ allCached &&= cached;
31973
+ data.label = toDiscogsLabel2(payload, labelId, labelFacts.name);
31974
+ } catch (error) {
31975
+ errors.push(failureOf2(error, labelUrl));
31976
+ }
31977
+ const releasesUrl = `${DISCOGS_ROOT2}/labels/${labelId}/releases?per_page=100&page=1`;
31978
+ try {
31979
+ const { cached, data: payload } = await fetchEvidenceJson(deps.http, "discogs", releasesUrl, headers);
31980
+ allCached &&= cached;
31981
+ const { facts, ids } = toDiscogsReleases2(payload);
31982
+ data.releases = facts;
31983
+ for (const id of ids) {
31984
+ releaseIds.add(id);
31985
+ }
31986
+ } catch (error) {
31987
+ errors.push(failureOf2(error, releasesUrl));
31988
+ }
31989
+ if (releaseIds.size > 0) {
31990
+ const styled = await readDiscogsStyles2(deps, releaseIds, data.label?.name ?? labelFacts.name);
31991
+ allCached &&= styled.cached;
31992
+ errors.push(...styled.errors);
31993
+ data.styles = styled.styles;
31994
+ }
31995
+ return {
31996
+ cached: allCached,
31997
+ data,
31998
+ ...errors.length > 0 ? { errors } : {},
31999
+ status: discogsStatus2(data, errors)
32000
+ };
32001
+ }
32002
+ function discogsStatus2(data, errors) {
32003
+ if (Object.keys(data).length === 0) {
32004
+ return "error";
32005
+ }
32006
+ return errors.length > 0 ? "partial" : "ok";
32007
+ }
32008
+ function discogsSearchName2(name) {
32009
+ return name.replace(/\s*\(\d+\)$/, "").replace(/^[^\p{L}\p{N}]+/u, "");
32010
+ }
32011
+ async function readDiscogsStyles2(deps, releaseIds, labelName) {
32012
+ const headers = discogsHeaders2(deps);
32013
+ const styled = new Map;
32014
+ const errors = [];
32015
+ let allCached = true;
32016
+ let viaSearch = 0;
32017
+ const searchUrl = `${DISCOGS_ROOT2}/database/search?type=release&label=${encodeURIComponent(discogsSearchName2(labelName))}&per_page=100`;
32018
+ try {
32019
+ const { cached, data } = await fetchEvidenceJson(deps.http, "discogs", searchUrl, headers);
32020
+ allCached &&= cached;
32021
+ for (const result of data.results ?? []) {
32022
+ if (typeof result.id === "number" && releaseIds.has(result.id) && !styled.has(result.id)) {
32023
+ styled.set(result.id, { genres: result.genre ?? [], styles: result.style ?? [] });
32024
+ }
32025
+ }
32026
+ viaSearch = styled.size;
32027
+ } catch (error) {
32028
+ errors.push(failureOf2(error, searchUrl));
32029
+ }
32030
+ const target = Math.min(DISCOGS_STYLE_TARGET2, releaseIds.size);
32031
+ const unread = [...releaseIds].filter((id) => !styled.has(id));
32032
+ let reads = 0;
32033
+ for (const id of unread) {
32034
+ if (styled.size >= target || reads >= DISCOGS_RELEASE_READS2) {
32035
+ break;
32036
+ }
32037
+ reads += 1;
32038
+ const releaseUrl = `${DISCOGS_ROOT2}/releases/${id}`;
32039
+ try {
32040
+ const { cached, data } = await fetchEvidenceJson(deps.http, "discogs", releaseUrl, headers);
32041
+ allCached &&= cached;
32042
+ styled.set(id, { genres: data.genres ?? [], styles: data.styles ?? [] });
32043
+ } catch (error) {
32044
+ errors.push(failureOf2(error, releaseUrl));
32045
+ }
32046
+ }
32047
+ const rows = [...styled.values()];
32048
+ return {
32049
+ cached: allCached,
32050
+ errors,
32051
+ styles: {
32052
+ genres: tally2(rows.flatMap((row) => row.genres)),
32053
+ labelReleasesListed: releaseIds.size,
32054
+ releasesRead: rows.length,
32055
+ styles: tally2(rows.flatMap((row) => row.styles)).slice(0, 25),
32056
+ viaRelease: rows.length - viaSearch,
32057
+ viaSearch
32058
+ }
32059
+ };
32060
+ }
32061
+ function facetCounts2(rows) {
32062
+ return (rows ?? []).flatMap((row) => row.name && typeof row.count === "number" ? [{ count: row.count, name: row.name }] : []).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
32063
+ }
32064
+ function parseBeatportTracksPage2(html) {
32065
+ const island = /<script id="__NEXT_DATA__"[^>]*>([\s\S]*?)<\/script>/.exec(html);
32066
+ if (!island?.[1]) {
32067
+ return null;
32068
+ }
32069
+ let queries;
32070
+ try {
32071
+ const parsed = JSON.parse(island[1]);
32072
+ queries = parsed.props?.pageProps?.dehydratedState?.queries ?? [];
32073
+ } catch {
32074
+ return null;
32075
+ }
32076
+ const tracks = queries.find((query) => query.queryKey?.[0] === "tracks" && query.state?.data?.facets?.fields)?.state?.data;
32077
+ if (!tracks) {
32078
+ return null;
32079
+ }
32080
+ const fields = tracks.facets?.fields;
32081
+ const genres = facetCounts2(fields?.genre);
32082
+ const total = genres.reduce((sum, genre) => sum + genre.count, 0);
32083
+ return {
32084
+ genres: genres.map((genre) => ({
32085
+ ...genre,
32086
+ share: total > 0 ? Math.round(genre.count / total * 1000) / 1000 : 0
32087
+ })),
32088
+ subGenres: facetCounts2(fields?.sub_genre),
32089
+ topArtists: facetCounts2(fields?.artists).slice(0, 15),
32090
+ trackCount: tracks.count ?? total
32091
+ };
32092
+ }
32093
+ async function gatherBeatport2(deps, mb) {
32094
+ if (!mb.label) {
32095
+ return {
32096
+ note: "MusicBrainz label unavailable, so no Beatport link to follow",
32097
+ status: "skipped"
32098
+ };
32099
+ }
32100
+ const labelUrl = beatportLabelUrlFrom2(linkOf2(mb.label.links, "beatport.com"));
32101
+ if (labelUrl === null) {
32102
+ return { note: "The MusicBrainz label has no Beatport link.", status: "no_link" };
32103
+ }
32104
+ if (deps.scraper === null) {
32105
+ return {
32106
+ note: "Beatport needs Firecrawl: set FIRECRAWL_API_KEY or install the firecrawl CLI.",
32107
+ status: "not_configured"
32108
+ };
32109
+ }
32110
+ const scraper = deps.scraper;
32111
+ const tracksUrl = `${labelUrl}/tracks`;
32112
+ try {
32113
+ const { cached, text } = await fetchEvidenceText(deps.http, "beatport", `SCRAPE ${tracksUrl}`, (signal) => scraper(tracksUrl, signal), (html) => parseBeatportTracksPage2(html) !== null);
32114
+ const facts = parseBeatportTracksPage2(text);
32115
+ if (facts === null) {
32116
+ return {
32117
+ errors: [
32118
+ {
32119
+ kind: "parse",
32120
+ message: "The Beatport page carried no tracks facet (a missing label or a layout change)",
32121
+ request: tracksUrl
32122
+ }
32123
+ ],
32124
+ status: "error"
32125
+ };
32126
+ }
32127
+ return { cached, data: { ...facts, labelUrl, tracksUrl }, status: "ok" };
32128
+ } catch (error) {
32129
+ return { errors: [failureOf2(error, tracksUrl)], status: "error" };
32130
+ }
32131
+ }
32132
+ async function gatherApple2(deps, mb) {
32133
+ if (!mb.releases) {
32134
+ return {
32135
+ note: "MusicBrainz releases unavailable, so no barcodes to look up",
32136
+ status: "skipped"
32137
+ };
32138
+ }
32139
+ const seen = new Set;
32140
+ const targets = mb.releases.releases.filter((release) => {
32141
+ if (!release.barcode || seen.has(release.barcode)) {
32142
+ return false;
32143
+ }
32144
+ seen.add(release.barcode);
32145
+ return true;
32146
+ });
32147
+ if (targets.length === 0) {
32148
+ return { note: "No sampled MusicBrainz release carries a barcode.", status: "no_link" };
32149
+ }
32150
+ const releases = [];
32151
+ const errors = [];
32152
+ let allCached = true;
32153
+ for (const target of targets.slice(0, APPLE_LOOKUPS2)) {
32154
+ const barcode = target.barcode ?? "";
32155
+ const url = `https://itunes.apple.com/lookup?upc=${encodeURIComponent(barcode)}&entity=album`;
32156
+ try {
32157
+ const { cached, data } = await fetchEvidenceJson(deps.http, "apple", url);
32158
+ allCached &&= cached;
32159
+ const hit = (data.results ?? []).find((result) => result.wrapperType === "collection");
32160
+ releases.push(hit ? {
32161
+ artistName: hit.artistName,
32162
+ barcode,
32163
+ collectionName: hit.collectionName,
32164
+ copyright: hit.copyright,
32165
+ found: true,
32166
+ mbTitle: target.title,
32167
+ primaryGenreName: hit.primaryGenreName
32168
+ } : { barcode, found: false, mbTitle: target.title });
32169
+ } catch (error) {
32170
+ errors.push(failureOf2(error, url));
32171
+ }
32172
+ }
32173
+ const looked = Math.min(targets.length, APPLE_LOOKUPS2);
32174
+ return {
32175
+ cached: allCached,
32176
+ data: {
32177
+ found: releases.filter((release) => release.found).length,
32178
+ genres: tally2(releases.flatMap((release) => release.primaryGenreName ?? [])),
32179
+ looked,
32180
+ releases
32181
+ },
32182
+ ...errors.length > 0 ? { errors } : {},
32183
+ status: statusFrom2(looked, errors.length)
32184
+ };
32185
+ }
32186
+ function skipped2() {
32187
+ return { note: "Not requested (--sources).", status: "skipped" };
32188
+ }
32189
+ async function resolveTarget2(input, deps) {
32190
+ const trimmed = input.trim();
32191
+ if (MBID_PATTERN4.test(trimmed)) {
32192
+ return { input: trimmed, mbLabelId: trimmed.toLowerCase() };
32193
+ }
32194
+ const label = await deps.resolveLabel(trimmed);
32195
+ if (!label.mbLabelId) {
32196
+ throw new Error(`Label '${label.slug}' has no MusicBrainz identity (mb_label_id), so nothing says which same-named label to research. Resolve it by hand first (docs/label-entity.md).`);
32197
+ }
32198
+ return {
32199
+ id: label.id,
32200
+ input: trimmed,
32201
+ mbLabelId: label.mbLabelId.toLowerCase(),
32202
+ name: label.name,
32203
+ seedState: label.seedState,
32204
+ slug: label.slug
32205
+ };
32206
+ }
32207
+ async function gatherLabelEvidence2(input, options, deps) {
32208
+ const before = { cacheHits: deps.http.stats.cacheHits, network: deps.http.stats.requests };
32209
+ const label = await resolveTarget2(input, deps);
32210
+ const wants = (source) => options.sources.includes(source);
32211
+ const needsMb = wants("musicbrainz") || wants("discogs") || wants("beatport") || wants("apple");
32212
+ const musicbrainz = needsMb ? await gatherMusicBrainz2(deps, label.mbLabelId, options) : skipped2();
32213
+ const mb = musicbrainz.data ?? {};
32214
+ const [discogs, beatport, apple] = await Promise.all([
32215
+ wants("discogs") ? gatherDiscogs2(deps, mb) : Promise.resolve(skipped2()),
32216
+ wants("beatport") ? gatherBeatport2(deps, mb) : Promise.resolve(skipped2()),
32217
+ wants("apple") ? gatherApple2(deps, mb) : Promise.resolve(skipped2())
32218
+ ]);
32219
+ const sources = { apple, beatport, discogs, musicbrainz };
32220
+ const reports = Object.entries(sources);
32221
+ const errors = reports.flatMap(([source, report]) => (report.errors ?? []).map((failure) => ({ ...failure, source })));
32222
+ const requested = reports.filter(([source]) => wants(source));
32223
+ const answered = requested.filter(([, report]) => ["no_link", "ok", "partial"].includes(report.status));
32224
+ return {
32225
+ errors,
32226
+ fetchedAt: new Date(deps.http.now()).toISOString(),
32227
+ label: { ...label, name: label.name ?? mb.label?.name },
32228
+ ok: answered.length > 0,
32229
+ partial: answered.length < requested.length || errors.length > 0,
32230
+ requests: {
32231
+ cacheHits: deps.http.stats.cacheHits - before.cacheHits,
32232
+ network: deps.http.stats.requests - before.network
32233
+ },
32234
+ sources
32235
+ };
32236
+ }
32237
+ function firecrawlApiScraper2(apiKey, http) {
32238
+ return async (url, signal) => {
32239
+ const response = await http.fetch(FIRECRAWL_SCRAPE_URL2, {
32240
+ body: JSON.stringify({ formats: ["rawHtml"], url }),
32241
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
32242
+ method: "POST",
32243
+ signal
32244
+ });
32245
+ if (!response.ok) {
32246
+ return { headers: response.headers, status: response.status, text: await response.text() };
32247
+ }
32248
+ const payload = await response.json();
32249
+ return {
32250
+ headers: response.headers,
32251
+ status: payload.data?.metadata?.statusCode ?? 200,
32252
+ text: payload.data?.rawHtml ?? ""
32253
+ };
32254
+ };
32255
+ }
32256
+ function firecrawlCliScraper2(binary) {
32257
+ return (url, signal) => new Promise((resolve, reject) => {
32258
+ const child = spawn2(binary, ["scrape", "-f", "rawHtml", url], {
32259
+ signal,
32260
+ stdio: ["ignore", "pipe", "pipe"]
32261
+ });
32262
+ const out = [];
32263
+ const err = [];
32264
+ child.stdout.on("data", (chunk) => out.push(chunk));
32265
+ child.stderr.on("data", (chunk) => err.push(chunk));
32266
+ child.on("error", reject);
32267
+ child.on("close", (code) => {
32268
+ if (code === 0) {
32269
+ resolve({
32270
+ headers: { get: () => null },
32271
+ status: 200,
32272
+ text: Buffer.concat(out).toString("utf8")
32273
+ });
32274
+ return;
32275
+ }
32276
+ const tail = Buffer.concat(err).toString("utf8").trim().split(`
32277
+ `).slice(-2).join(" ");
32278
+ reject(new Error(`firecrawl CLI exited ${code}: ${tail}`));
32279
+ });
32280
+ });
32281
+ }
32282
+ function defaultBeatportScraper2(env, http) {
32283
+ if (env.firecrawlApiKey) {
32284
+ return firecrawlApiScraper2(env.firecrawlApiKey, http);
32285
+ }
32286
+ return env.firecrawlBinary ? firecrawlCliScraper2(env.firecrawlBinary) : null;
32287
+ }
32288
+ async function createLabelEvidenceDeps2(refresh) {
32289
+ const [{ readOptionalEnv }, { resolveLabel }] = await Promise.all([
32290
+ Promise.resolve().then(() => (init_env(), exports_env)),
32291
+ Promise.resolve().then(() => (init_admin_labels3(), exports_admin_labels))
32292
+ ]);
32293
+ const http = createEvidenceHttp({ deadline: deadlineAt(), refresh });
32294
+ const discogsToken = readOptionalEnv("DISCOGS_USER_TOKEN");
32295
+ if (discogsToken) {
32296
+ http.policies = { ...http.policies, discogs: { ...http.policies.discogs, intervalMs: 1100 } };
32297
+ }
32298
+ return {
32299
+ discogsToken,
32300
+ http,
32301
+ resolveLabel,
32302
+ scraper: defaultBeatportScraper2({
32303
+ firecrawlApiKey: readOptionalEnv("FIRECRAWL_API_KEY"),
32304
+ firecrawlBinary: Bun.which("firecrawl")
32305
+ }, http)
32306
+ };
32307
+ }
32308
+ function countLine2(counts, limit) {
32309
+ return counts.slice(0, limit).map((entry) => `${entry.name} ${entry.count}`).join(", ");
32310
+ }
32311
+ function musicbrainzDetailLines2(mb) {
32312
+ const lines = [];
32313
+ if (mb?.label?.labelRelations.length) {
32314
+ lines.push(` label relations: ${mb.label.labelRelations.map((relation) => `${relation.type}: ${relation.name} (${relation.mbid})`).join("; ")}`);
32315
+ }
32316
+ if (mb?.census) {
32317
+ lines.push(` first credits: ${mb.census.firstCredits.map((credit) => `${credit.artistName} (${credit.artistMbid}) ${credit.recordings}`).join("; ")}; uncredited ${mb.census.uncreditedRecordings}`);
32318
+ }
32319
+ for (const release of mb?.releases?.releases ?? []) {
32320
+ lines.push(` release: ${release.artist} — ${release.title}; catno ${release.catno ?? "none"}; ${release.date ?? "undated"}`);
32321
+ }
32322
+ return lines;
32323
+ }
32324
+ function labelEvidenceLines2(evidence) {
32325
+ const { apple, beatport, discogs, musicbrainz } = evidence.sources;
32326
+ const mb = musicbrainz.data;
32327
+ const name = evidence.label.name ?? evidence.label.mbLabelId;
32328
+ const lines = [`${name} (${evidence.label.mbLabelId})`];
32329
+ const mbParts = [];
32330
+ if (mb?.label) {
32331
+ mbParts.push([mb.label.type, mb.label.area, mb.label.lifeSpan.begin].filter(Boolean).join(", "));
32332
+ }
32333
+ if (mb?.releases) {
32334
+ const top = mb.releases.firstCreditArtists.slice(0, FIRST_CREDIT_ARTISTS2).map((artist) => `${artist.name} ${artist.releases}`).join(", ");
32335
+ mbParts.push(`${mb.releases.releaseCount} releases; first credits: ${top || "none"}`);
32336
+ }
32337
+ if (mb?.census) {
32338
+ mbParts.push(`census ${mb.census.recordingsCounted} recordings over ${mb.census.releasesRead} releases${mb.census.caveat ? ` (${mb.census.caveat})` : ""}`);
32339
+ }
32340
+ lines.push(` musicbrainz: ${musicbrainz.status}${mbParts.length ? ` — ${mbParts.join("; ")}` : ""}`);
32341
+ lines.push(...musicbrainzDetailLines2(mb));
32342
+ const dg = discogs.data;
32343
+ const dgDetail = dg?.styles ? `styles: ${countLine2(dg.styles.styles, 6)} (${dg.styles.releasesRead} releases)` : dg?.candidates ? `unverified candidates: ${dg.candidates.map((c) => c.title).join(", ") || "none"}` : discogs.note;
32344
+ lines.push(` discogs: ${discogs.status}${dgDetail ? ` — ${dgDetail}` : ""}`);
32345
+ const bp = beatport.data;
32346
+ const bpDetail = bp ? `${bp.trackCount} tracks; genres: ${bp.genres.slice(0, 5).map((genre) => `${genre.name} ${Math.round(genre.share * 100)}%`).join(", ")}` : beatport.note;
32347
+ lines.push(` beatport: ${beatport.status}${bpDetail ? ` — ${bpDetail}` : ""}`);
32348
+ const ap = apple.data;
32349
+ const apDetail = ap ? `${ap.found}/${ap.looked} found; genres: ${countLine2(ap.genres, 4) || "none"}` : apple.note;
32350
+ lines.push(` apple: ${apple.status}${apDetail ? ` — ${apDetail}` : ""}`);
32351
+ for (const failure of evidence.errors) {
32352
+ lines.push(` ! ${failure.source}: ${failure.message}`);
32353
+ }
32354
+ return lines;
32355
+ }
32356
+ var MBID_PATTERN4, MB_ROOT2 = "https://musicbrainz.org/ws/2", DISCOGS_ROOT2 = "https://api.discogs.com", FIRECRAWL_SCRAPE_URL2 = "https://api.firecrawl.dev/v2/scrape", VARIOUS_ARTISTS_MBID2 = "89ad4ac3-39f7-470e-963a-56509c546377", RELEASE_SAMPLE2 = 12, FIRST_CREDIT_ARTISTS2 = 25, APPLE_LOOKUPS2 = 5, DISCOGS_RELEASE_SAMPLE2 = 8, DISCOGS_STYLE_TARGET2 = 10, DISCOGS_RELEASE_READS2 = 8, PROFILE_CHARS2 = 800, EVIDENCE_SOURCES2;
32357
+ var init_admin_label_evidence2 = __esm(() => {
32358
+ init_deadline();
32359
+ init_evidence_http();
32360
+ MBID_PATTERN4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32361
+ EVIDENCE_SOURCES2 = ["musicbrainz", "discogs", "beatport", "apple"];
32362
+ });
32363
+
32364
+ // src/commands/admin-label-evidence-batch.ts
32365
+ import { appendFileSync, mkdirSync as mkdirSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
32366
+ import { basename as basename2, dirname as dirname3, join as join7, resolve as resolve4 } from "node:path";
32367
+ import { randomUUID as randomUUID3 } from "node:crypto";
32368
+ function atomicWrite(path, text) {
32369
+ const temporary = `${path}.${randomUUID3()}.tmp`;
32370
+ writeFileSync2(temporary, text, { mode: 384 });
32371
+ renameSync(temporary, path);
32372
+ }
32373
+ async function gatherLabelEvidenceBatch(inputs, options, deps) {
32374
+ const out = resolve4(options.out);
32375
+ const manifest = resolve4(options.manifest ?? join7(out, "manifest.jsonl"));
32376
+ mkdirSync2(out, { recursive: true });
32377
+ mkdirSync2(dirname3(manifest), { recursive: true });
32378
+ const runId = basename2(dirname3(manifest));
32379
+ const slice = out;
32380
+ const attempt = randomUUID3();
32381
+ const record = (event) => appendFileSync(manifest, `${JSON.stringify({ at: new Date().toISOString(), attempt, runId, slice, ...event })}
32382
+ `, { mode: 384 });
32383
+ const labels = [...new Set(inputs)];
32384
+ const lines = [];
32385
+ let ok = true;
32386
+ record({ labels, state: "started" });
32387
+ for (const input of labels) {
32388
+ record({ input, state: "pending" });
32389
+ }
32390
+ for (const input of labels) {
32391
+ let evidence;
32392
+ try {
32393
+ evidence = await gatherLabelEvidence2(input, options, deps);
32394
+ } catch (error) {
32395
+ ok = false;
32396
+ const message = error instanceof Error ? error.message : String(error);
32397
+ const entry = {
32398
+ id: input,
32399
+ input,
32400
+ message,
32401
+ path: null,
32402
+ sources: Object.fromEntries(EVIDENCE_SOURCES2.map((source) => [source, "skipped"])),
32403
+ state: "failed"
32404
+ };
32405
+ record(entry);
32406
+ lines.push(`manifest ${JSON.stringify(entry)}`);
32407
+ continue;
32408
+ }
32409
+ const key = encodeURIComponent(evidence.label.mbLabelId);
32410
+ const path = join7(out, `${key}.json`);
32411
+ const summaryPath = join7(out, `${key}.txt`);
32412
+ const summary = labelEvidenceLines2(evidence);
32413
+ atomicWrite(path, `${JSON.stringify(evidence, null, 2)}
32414
+ `);
32415
+ atomicWrite(summaryPath, `${summary.join(`
32416
+ `)}
32417
+ `);
32418
+ const entry = {
32419
+ id: evidence.label.mbLabelId,
32420
+ input,
32421
+ path,
32422
+ sources: Object.fromEntries(Object.entries(evidence.sources).map(([name, source]) => [name, source.status])),
32423
+ state: evidence.ok ? "ready" : "failed",
32424
+ summaryPath
32425
+ };
32426
+ record(entry);
32427
+ lines.push(...summary, `manifest ${JSON.stringify(entry)}`);
32428
+ ok &&= evidence.ok;
32429
+ }
32430
+ record({ labels, ok, state: "completed" });
32431
+ lines.push(`round manifest: ${manifest}`);
32432
+ return { lines, ok };
32433
+ }
32434
+ async function labelEvidenceBatchCommand(inputs, options) {
32435
+ return gatherLabelEvidenceBatch(inputs, options, await createLabelEvidenceDeps2(options.refresh));
32436
+ }
32437
+ var init_admin_label_evidence_batch = __esm(() => {
32438
+ init_admin_label_evidence2();
32439
+ });
32440
+
31594
32441
  // src/commands/admin-albums.ts
31595
32442
  async function describeAlbumCommand(slug, options) {
31596
32443
  return adminApiPost(`/api/v1/admin/albums/${encodeURIComponent(slug)}/bio`, buildBioBody2(options));
@@ -35601,15 +36448,36 @@ JSON field reference:
35601
36448
  console.log(`${label.slug} ${label.seedState} ${looked ?? ""}${rules}`.trimEnd());
35602
36449
  }
35603
36450
  });
35604
- labels.command("evidence").description("Gather a label's MusicBrainz, Discogs, Beatport and Apple evidence for triage (cached, rate-limited)").argument("<label>", "The label's MusicBrainz MBID, slug, or lbl_\u2026 id").option("--census", "Also count FIRST credits per recording over the label's releases", false).option("--census-pages <n>", "MusicBrainz pages the census may read, 1-5", "5").option("--sources <list>", "Comma list of musicbrainz,discogs,beatport,apple (default all)").option("--refresh", "Ignore cached responses and fetch fresh", false).option("--json", "Print JSON", false).action(async (input, options) => {
36451
+ labels.command("evidence").description("Gather a label's MusicBrainz, Discogs, Beatport and Apple evidence for triage (cached, rate-limited)").argument("<labels...>", "MusicBrainz MBIDs, slugs, or lbl_\u2026 ids (several require --out)").option("--census", "Also count FIRST credits per recording over the label's releases", false).option("--census-pages <n>", "MusicBrainz pages the census may read, 1-5", "5").option("--sources <list>", "Comma list of musicbrainz,discogs,beatport,apple (default all)").option("--refresh", "Ignore cached responses and fetch fresh", false).option("--out <directory>", "Write each label JSON and summary atomically; print summaries").option("--manifest <file>", "Append slice states to a shared round JSONL manifest").option("--json", "Print JSON (single label without --out)", false).action(async (inputs, options) => {
35605
36452
  await Promise.resolve().then(() => init_admin_label_evidence());
35606
36453
  const censusPages = parseCensusPages(options.censusPages);
35607
- const evidence = await labelEvidenceCommand(input, {
36454
+ const evidenceOptions = {
35608
36455
  census: options.census,
35609
36456
  censusPages,
35610
36457
  refresh: options.refresh,
35611
36458
  sources: parseEvidenceSources(options.sources)
35612
- });
36459
+ };
36460
+ if (options.out) {
36461
+ if (options.json) {
36462
+ throw new Error("Use --out for batch summaries and saved JSON; omit --json");
36463
+ }
36464
+ await Promise.resolve().then(() => init_admin_label_evidence_batch());
36465
+ const result = await labelEvidenceBatchCommand(inputs, {
36466
+ ...evidenceOptions,
36467
+ manifest: options.manifest,
36468
+ out: options.out
36469
+ });
36470
+ if (!result.ok) {
36471
+ process.exitCode = 1;
36472
+ }
36473
+ console.log(result.lines.join(`
36474
+ `));
36475
+ return;
36476
+ }
36477
+ if (inputs.length !== 1 || options.manifest) {
36478
+ throw new Error("Several labels or --manifest require --out <directory>");
36479
+ }
36480
+ const evidence = await labelEvidenceCommand(inputs[0] ?? "", evidenceOptions);
35613
36481
  if (!evidence.ok) {
35614
36482
  process.exitCode = 1;
35615
36483
  }
@@ -38596,6 +39464,8 @@ function normalizeCommanderError(error) {
38596
39464
  return new Error(message);
38597
39465
  }
38598
39466
  var stringOptions = new Set([
39467
+ "--manifest",
39468
+ "--out",
38599
39469
  "--timeout",
38600
39470
  "--isrc-refresh-limit",
38601
39471
  "--action",
package/package.json CHANGED
@@ -31,5 +31,5 @@
31
31
  "url": "git+https://github.com/mauricekleine/fluncle.git"
32
32
  },
33
33
  "type": "module",
34
- "version": "0.283.0"
34
+ "version": "0.284.0"
35
35
  }