@audiofool/moondog 0.4.0-beta.3 → 0.4.0-beta.4

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 (93) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +95 -103
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +63 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +28 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1003 -267
  18. package/src/core/play-follower.mjs +73 -37
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +89 -26
  34. package/src/i18n/screen/ja.mjs +88 -25
  35. package/src/i18n/screen/pt.mjs +89 -26
  36. package/src/i18n/screen/zh.mjs +88 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/song-id.mjs +13 -0
  44. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  45. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  46. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  47. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  48. package/src/integrations/playlist-links.mjs +93 -30
  49. package/src/integrations/public-playlists.mjs +21 -15
  50. package/src/integrations/spotify/account-data-history.mjs +9 -10
  51. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  52. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  53. package/src/integrations/spotify/history-archive.mjs +8 -18
  54. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  55. package/src/integrations/spotify/service.mjs +29 -11
  56. package/src/integrations/spotify/web-api-client.mjs +2 -2
  57. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  58. package/src/integrations/youtube-music/takeout.mjs +12 -8
  59. package/src/memory/local-memory-store.mjs +479 -27
  60. package/src/memory/reflection-worker.mjs +1 -0
  61. package/src/profile/apple-library-import.mjs +56 -2
  62. package/src/profile/history-import.mjs +58 -27
  63. package/src/profile/listener-corrections.mjs +2 -4
  64. package/src/profile/listener-profile-build.mjs +128 -45
  65. package/src/profile/listener-profile-store.mjs +25 -4
  66. package/src/profile/listener-profile-verification.mjs +11 -5
  67. package/src/profile/listener-profile-worker.mjs +24 -8
  68. package/src/profile/listening-history-store.mjs +944 -367
  69. package/src/profile/listening-profile-projection.mjs +123 -156
  70. package/src/profile/local-file-import.mjs +172 -0
  71. package/src/profile/moondog-suggestions.mjs +40 -11
  72. package/src/profile/profile-exploration.mjs +36 -6
  73. package/src/profile/recorded-measures.mjs +5 -0
  74. package/src/profile/spotify-archive-taste.mjs +41 -65
  75. package/src/runtime/pi/agent-runtime.mjs +360 -215
  76. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  77. package/src/runtime/pi/memory-agent-runtime.mjs +43 -3
  78. package/src/runtime/pi/playback-rules.mjs +100 -0
  79. package/src/runtime/pi/profile-build-runtime.mjs +81 -24
  80. package/src/surfaces/cli/brand-components.mjs +9 -6
  81. package/src/surfaces/cli/command-completions.mjs +8 -1
  82. package/src/surfaces/cli/format-output.mjs +207 -34
  83. package/src/surfaces/cli/history-import-view.mjs +130 -21
  84. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  85. package/src/surfaces/cli/listener-profile-command.mjs +67 -10
  86. package/src/surfaces/cli/listening-menu.mjs +3 -0
  87. package/src/surfaces/cli/profile-command.mjs +1 -0
  88. package/src/surfaces/cli/spotify-command.mjs +17 -25
  89. package/src/surfaces/cli/taste-period.mjs +22 -0
  90. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  91. package/src/surfaces/cli/tui.mjs +557 -170
  92. package/src/surfaces/html/tasteprint.mjs +181 -93
  93. package/src/surfaces/import-source-history.mjs +80 -0
@@ -1,12 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readImportSourceHistory } from "./import-source-history.mjs";
2
3
  import { exploreProfileCatalog, profileExplorationInput } from "../profile/profile-exploration.mjs";
3
4
  import { createListenerProfileInput, savedListenerChoices } from "../profile/listener-profile-build.mjs";
4
5
  import { lyricSeedsFromProfile } from "./lyric-profile.mjs";
5
- import { cachedAvoidGate, createAvoidGate, listeningVersion } from "./listener-avoids.mjs";
6
+ import { allowedDiscoveryTracks, cachedAvoidGate, createAvoidGate, listeningVersion } from "./listener-avoids.mjs";
6
7
  import { recordListenerChoice } from "../profile/listener-corrections.mjs";
7
8
  import { listenedNames } from "../profile/taste-compiler.mjs";
8
9
  import { normalizedTrackTitle } from "./track-title.mjs";
9
10
  import { collectionCoverage } from "../profile/music-providers.mjs";
11
+ import { curatedPreferenceItems, preferenceIdentity } from "../profile/spotify-archive-taste.mjs";
12
+ import { isHeardMixSlot } from "../profile/moondog-suggestions.mjs";
10
13
  import { lstat } from "node:fs/promises";
11
14
  import path from "node:path";
12
15
 
@@ -1007,11 +1010,10 @@ export function listenerAssertionAvoids(
1007
1010
  : gate.avoidsTrack({ title: label, artist_credit: artistCredit });
1008
1011
  }
1009
1012
 
1010
- function normalizeAppleCorrectionLabels(listening, projection) {
1011
- if (!listening || typeof projection.resolveTrackLabel !== "function") return listening;
1013
+ function appleCorrectionLabelResolver(projection) {
1012
1014
  const resolved = new Map();
1013
- function normalize(item) {
1014
- if (item?.entity_type !== "track" || !item.correction_id) return item;
1015
+ return (item) => {
1016
+ if (item?.entity_type !== "track" || !item.correction_id || typeof projection.resolveTrackLabel !== "function") return item;
1015
1017
  if (!resolved.has(item.correction_id)) {
1016
1018
  const match = projection.resolveTrackLabel({
1017
1019
  label: item.label,
@@ -1021,7 +1023,12 @@ function normalizeAppleCorrectionLabels(listening, projection) {
1021
1023
  }
1022
1024
  const title = resolved.get(item.correction_id);
1023
1025
  return title === null ? item : { ...item, label: title };
1024
- }
1026
+ };
1027
+ }
1028
+
1029
+ function normalizeAppleCorrectionLabels(listening, projection) {
1030
+ if (!listening || typeof projection.resolveTrackLabel !== "function") return listening;
1031
+ const normalize = appleCorrectionLabelResolver(projection);
1025
1032
  return {
1026
1033
  ...listening,
1027
1034
  listener_assertions: {
@@ -1084,6 +1091,16 @@ function interleaveUnique(lists, maximum, field) {
1084
1091
  return result;
1085
1092
  }
1086
1093
 
1094
+ // Keep the source mix and use the strongest signal when several sources name the same recording.
1095
+ function interleavePreferences(sources, maximum) {
1096
+ const strongest = new Map();
1097
+ for (const item of sources.flat()) {
1098
+ const key = preferenceIdentity(item);
1099
+ if (!strongest.has(key)) strongest.set(key, item);
1100
+ }
1101
+ return interleaveUnique(sources, maximum, preferenceIdentity).map(item => strongest.get(preferenceIdentity(item)));
1102
+ }
1103
+
1087
1104
  function basisSummaryText(explanation) {
1088
1105
  const basis = explanation.basis_summary ?? {};
1089
1106
  const details = [];
@@ -1292,6 +1309,10 @@ export class AppleProjectionDomainServices {
1292
1309
  return this.#listeningHistoryStore?.listeningCoverage?.({ subjectId: this.#subjectId }) ?? null;
1293
1310
  }
1294
1311
 
1312
+ importSourceHistory(options) {
1313
+ return readImportSourceHistory({ ...options, listeningHistoryStore: this.#listeningHistoryStore, subjectId: this.#subjectId });
1314
+ }
1315
+
1295
1316
  recentAttention() {
1296
1317
  return this.#listeningHistoryStore?.recentAttention?.({ subjectId: this.#subjectId }) ?? null;
1297
1318
  }
@@ -1301,8 +1322,8 @@ export class AppleProjectionDomainServices {
1301
1322
  }
1302
1323
 
1303
1324
  // Moondog's suggestions ledger and the declared mix (src/profile/moondog-suggestions.mjs).
1304
- recordMoondogSuggestions(entries) {
1305
- return this.#listeningHistoryStore?.recordMoondogSuggestions?.({ entries }) ?? null;
1325
+ recordMoondogSuggestions(entries, options = {}) {
1326
+ return this.#listeningHistoryStore?.recordMoondogSuggestions?.({ ...options, entries }) ?? null;
1306
1327
  }
1307
1328
 
1308
1329
  recordSuggestionOutcome(outcome) {
@@ -1319,7 +1340,7 @@ export class AppleProjectionDomainServices {
1319
1340
  const slots = this.#listeningHistoryStore?.listeningMix?.({ subjectId: this.#subjectId, tracks }) ??
1320
1341
  tracks.map(() => "unknown");
1321
1342
  return slots.map((slot, index) => {
1322
- if (!["new", "known_artist", "unknown"].includes(slot)) return slot;
1343
+ if (slot === "familiar" || slot === "returning") return slot;
1323
1344
  const plays = this.#libraryPlayCount(tracks[index]);
1324
1345
  return plays >= 3 ? "familiar" : plays > 0 ? "heard" : slot;
1325
1346
  });
@@ -1832,7 +1853,7 @@ export class AppleProjectionDomainServices {
1832
1853
  return normalizeAppleCorrectionLabels({ listener_assertions: { avoids } }, this.#projection)
1833
1854
  .listener_assertions.avoids;
1834
1855
  });
1835
- return tracks.filter((track) => !gate.avoidsTrack(track));
1856
+ return allowedDiscoveryTracks(gate, tracks, this.#listeningHistoryStore, this.#subjectId);
1836
1857
  }
1837
1858
 
1838
1859
  // Choices live with the listening history, so a library alone cannot save them.
@@ -1845,6 +1866,16 @@ export class AppleProjectionDomainServices {
1845
1866
  return recordListenerChoice(this.#listeningHistoryStore, { ...choice, subjectId: this.#subjectId });
1846
1867
  }
1847
1868
 
1869
+ tasteReviewChoices() {
1870
+ const active = this.#listeningHistoryStore?.listListenerCorrections?.({ subjectId: this.#subjectId, limit: null });
1871
+ if (!active) return null;
1872
+ return normalizeAppleCorrectionLabels({ listener_assertions: { active } }, this.#projection).listener_assertions.active;
1873
+ }
1874
+
1875
+ retractTasteReviewChoice(correctionId) {
1876
+ return this.#listeningHistoryStore.retractListenerCorrection({ subjectId: this.#subjectId, correctionId });
1877
+ }
1878
+
1848
1879
  // The choices in force, cheap enough to read when there is no saved reading.
1849
1880
  listenerChoices() {
1850
1881
  const store = this.#listeningHistoryStore;
@@ -1854,7 +1885,7 @@ export class AppleProjectionDomainServices {
1854
1885
  }
1855
1886
 
1856
1887
  isKnownDiscoveryTrack(track) {
1857
- return (this.#listeningHistoryStore?.listenedTracks?.({ subjectId: this.#subjectId }) ?? []).some(heard => exactTitleArtistMatch(track, heard));
1888
+ return isHeardMixSlot(this.listeningMix([track])[0]);
1858
1889
  }
1859
1890
 
1860
1891
  // Every Avoid in force, imported bans included, as the play paths read them.
@@ -1892,7 +1923,8 @@ export class AppleProjectionDomainServices {
1892
1923
  const accepted = [];
1893
1924
  let excludedLibraryMatches = 0;
1894
1925
  const allowed = this.filterDiscoveryTracks(prepared);
1895
- for (const track of allowed) {
1926
+ const historySlots = this.#listeningHistoryStore?.listeningMix?.({ subjectId: this.#subjectId, tracks: allowed });
1927
+ for (const [index, track] of allowed.entries()) {
1896
1928
  const query = Array.from(track.title).slice(0, 256).join("");
1897
1929
  const libraryResults = this.#projection.searchLibrary({
1898
1930
  query,
@@ -1908,7 +1940,8 @@ export class AppleProjectionDomainServices {
1908
1940
  const libraryMatch = libraryResults.tracks
1909
1941
  .map(safeTrack)
1910
1942
  .some((candidate) => exactTitleArtistMatch(track, candidate));
1911
- if (excludeKnown && libraryMatch) {
1943
+ const heard = isHeardMixSlot(historySlots?.[index]);
1944
+ if (excludeKnown && (libraryMatch || heard)) {
1912
1945
  excludedLibraryMatches += 1;
1913
1946
  continue;
1914
1947
  }
@@ -1916,7 +1949,7 @@ export class AppleProjectionDomainServices {
1916
1949
  ...track,
1917
1950
  knownness: {
1918
1951
  imported_library: libraryMatch ? "found_by_exact_title_artist" : "not_found_by_exact_title_artist",
1919
- listening_history: "not_checked",
1952
+ listening_history: historySlots ? (heard ? "found_by_exact_title_artist" : "not_found_by_exact_title_artist") : "not_checked",
1920
1953
  },
1921
1954
  });
1922
1955
  }
@@ -2061,6 +2094,7 @@ export class AppleProjectionDomainServices {
2061
2094
  return exploreProfileCatalog({
2062
2095
  listening,
2063
2096
  apple: this.#appleProfileCatalog(listening?.sections.listener_avoids), input,
2097
+ resolveChoice: appleCorrectionLabelResolver(this.#projection),
2064
2098
  });
2065
2099
  }
2066
2100
 
@@ -2073,11 +2107,11 @@ export class AppleProjectionDomainServices {
2073
2107
  return this.#listeningHistoryStore.listenerProfileStorage({ subjectId: this.#subjectId });
2074
2108
  }
2075
2109
 
2076
- getProfileBuildContext() {
2110
+ getProfileBuildContext(readingThrough = null) {
2077
2111
  const appleDigest = this.#projection.logicalDigest();
2078
2112
  const version = `${appleDigest}:${listeningVersion(this.#listeningHistoryStore)}`;
2079
- if (this.#profileBuildInput?.version !== version) {
2080
- const listening = this.#listeningHistoryStore.profileCatalog({ subjectId: this.#subjectId });
2113
+ if (this.#profileBuildInput?.version !== version || (readingThrough && !this.#profileBuildInput.input.historyDigests[readingThrough])) {
2114
+ const listening = this.#listeningHistoryStore.profileCatalog({ subjectId: this.#subjectId, readingThrough });
2081
2115
  const normalized = normalizeAppleCorrectionLabels({ listener_assertions: {
2082
2116
  preferences: listening.sections.listener_preferences, avoids: listening.sections.listener_avoids,
2083
2117
  } }, this.#projection).listener_assertions;
@@ -2087,13 +2121,13 @@ export class AppleProjectionDomainServices {
2087
2121
  subjectId: this.#subjectId,
2088
2122
  evidenceRevision: [appleDigest,
2089
2123
  this.#listeningHistoryStore.profileEvidenceRevision({ subjectId: this.#subjectId })],
2090
- listening, apple: this.#appleProfileCatalog(listening.sections.listener_avoids),
2124
+ listening, apple: this.#appleProfileCatalog(listening.sections.listener_avoids), appleRevision: appleDigest,
2091
2125
  }) };
2092
2126
  }
2093
2127
  return { store: this.getListenerProfileStore(), input: this.#profileBuildInput.input };
2094
2128
  }
2095
2129
 
2096
- async getProfileSummary(argumentsValue) {
2130
+ async getProfileSummary(argumentsValue, { includeReviewTracks = false } = {}) {
2097
2131
  const input = modelArguments(argumentsValue, new Set(["maxItems"]));
2098
2132
  const bounded = boundedLimit(
2099
2133
  input.maxItems,
@@ -2144,26 +2178,7 @@ export class AppleProjectionDomainServices {
2144
2178
  signal: `You explicitly said you like this ${item.entity_type}`,
2145
2179
  evidence_id: item.evidence_id,
2146
2180
  }));
2147
- const spotifyStrongPreferences = listening
2148
- ? listening.curated_preferences.saved_tracks
2149
- .filter(
2150
- (item) =>
2151
- !listenerAssertionAvoids(
2152
- listening,
2153
- "track",
2154
- item.label,
2155
- item.artist_credit,
2156
- ),
2157
- )
2158
- .map((item) => ({
2159
- label: item.label,
2160
- entity_type: "track",
2161
- artist_credit: item.artist_credit,
2162
- track_ref_id: item.track_ref_id,
2163
- signal: `Saved in ${item.source_label ?? "Spotify"} library`,
2164
- evidence_id: item.evidence_id,
2165
- }))
2166
- : [];
2181
+ const curatedStrongPreferences = curatedPreferenceItems(listening, listenerAssertionAvoids);
2167
2182
  const appleFamiliarity = familiarityItems.map((item) => {
2168
2183
  const playCount = item.observation_summary?.play_count;
2169
2184
  const result = {
@@ -2225,15 +2240,11 @@ export class AppleProjectionDomainServices {
2225
2240
  return {
2226
2241
  profile_version: listening ? "profile-projection/1" : raw.schema_version,
2227
2242
  max_items_applied: bounded,
2228
- strong_preferences: interleaveUnique(
2229
- [
2230
- listenerStrongPreferences,
2231
- appleStrongPreferences,
2232
- spotifyStrongPreferences,
2233
- ],
2234
- bounded,
2235
- (item) => JSON.stringify([item.entity_type, item.label, item.artist_credit ?? ""]),
2236
- ),
2243
+ // Only the local Taste clients browse the full catalog. Public and model summaries stay bounded.
2244
+ ...(includeReviewTracks && appleCatalog ? {
2245
+ reviewLibraryTracks: appleCatalog.sections.apple_tracks.map(({ label, artist_credit }) => ({ label, artist_credit })),
2246
+ } : {}),
2247
+ strong_preferences: interleavePreferences([listenerStrongPreferences, appleStrongPreferences, curatedStrongPreferences], bounded),
2237
2248
  familiarity: interleaveUnique(
2238
2249
  [appleFamiliarity, spotifyFamiliarity],
2239
2250
  bounded,
@@ -2260,6 +2271,7 @@ export class AppleProjectionDomainServices {
2260
2271
  listening.coverage.effective_listening_events,
2261
2272
  profiled_listening_events:
2262
2273
  listening.coverage.profiled_listening_events,
2274
+ events_with_played_duration: listening.coverage.events_with_played_duration,
2263
2275
  listening_hours: listening.coverage.listening_hours,
2264
2276
  listening_tracks: listening.coverage.distinct_tracks,
2265
2277
  resolved_listening_tracks: listening.coverage.resolved_tracks,
@@ -2474,10 +2486,9 @@ export class AppleProjectionDomainServices {
2474
2486
  "The playlist track count does not match the explicit user intent.",
2475
2487
  );
2476
2488
  }
2477
- const external = selections.map((selection) => trustedTracks.get(selection.trackRefId))
2478
- .filter((track) => track.candidate_scope === "external_catalog");
2479
- if (this.filterDiscoveryTracks(external).length !== external.length) {
2480
- fail("discovery_track_avoided", "An external discovery is currently marked Avoid. Choose another track.");
2489
+ const selectedTracks = selections.map(selection => trustedTracks.get(selection.trackRefId));
2490
+ if (this.filterDiscoveryTracks(selectedTracks).length !== selectedTracks.length) {
2491
+ fail("discovery_track_avoided", "A selected song is currently marked Avoid. Choose another track.");
2481
2492
  }
2482
2493
  const tracks = selections.map((selection, index) => {
2483
2494
  const track = trustedTracks.get(selection.trackRefId);
@@ -39,7 +39,7 @@ const catalog = [
39
39
  version: "1",
40
40
  state: "enabled",
41
41
  effect: "read_local",
42
- description: "Inspect aggregate Apple Music import readiness.",
42
+ description: "Inspect Apple Music readiness or read saved import receipts.",
43
43
  agent_tool: {
44
44
  name: "moondog_source_status",
45
45
  label: N_("Check your music sources"),
@@ -67,6 +67,17 @@ const catalog = [
67
67
  label: N_("Check what I remember"),
68
68
  },
69
69
  },
70
+ {
71
+ id: "skill.read",
72
+ version: "1",
73
+ state: "enabled",
74
+ effect: "read_local",
75
+ description: "Read one local learned practice by name when its index description matches the current request.",
76
+ agent_tool: {
77
+ name: "moondog_skill",
78
+ label: N_("Read a learned practice"),
79
+ },
80
+ },
70
81
  {
71
82
  id: "capability.status",
72
83
  version: "1",
@@ -239,7 +250,7 @@ const catalog = [
239
250
  state: "enabled",
240
251
  effect: "play_preview",
241
252
  description:
242
- "Play 30-second Apple Music previews of named songs or one album, as a queue in the host's player.",
253
+ "Play or append named Apple Music songs or an album in the host's player.",
243
254
  requires_music_preview: true,
244
255
  agent_tool: {
245
256
  name: "moondog_music_preview",
@@ -309,6 +320,11 @@ const catalog = [
309
320
  label: N_("Find music nearby"),
310
321
  },
311
322
  },
323
+ {
324
+ id: "listening.moment", version: "1", state: "enabled", effect: "write_local",
325
+ description: "Keep the listener's current situation and temporary directions in this conversation.",
326
+ agent_tool: { name: "moondog_listening_moment", label: N_("Update this listening session") },
327
+ },
312
328
  {
313
329
  id: "memory.inspect",
314
330
  version: "1",
@@ -0,0 +1,28 @@
1
+ import { listAppleLibraryImportHistory } from "./apple-library-source-status.mjs";
2
+
3
+ // Read only the listening receipts that can land on this page after the XML snapshots are merged.
4
+ export async function readImportSourceHistory({ listeningHistoryStore, subjectId, importsRoot, offset = 0, limit = 12 } = {}) {
5
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 20) {
6
+ throw new RangeError("Invalid import history page.");
7
+ }
8
+ let collections = [];
9
+ let collectionState;
10
+ try {
11
+ collections = await listAppleLibraryImportHistory({ subjectId, importsRoot });
12
+ } catch (error) {
13
+ if (error.code === "apple_library_multiple_subjects") collectionState = "multiple_subjects";
14
+ else if (error.code === "apple_library_history_unavailable") collectionState = "unavailable";
15
+ else throw error;
16
+ }
17
+ const start = Math.max(0, offset - collections.length);
18
+ const listening = listeningHistoryStore?.importSourceHistory({ subjectId, offset: start, limit: offset - start + limit })
19
+ ?? { total: 0, items: [] };
20
+ const total = listening.total + collections.length;
21
+ // Unknown save dates follow dated saves. Only those undated snapshots are sorted by observation.
22
+ const rows = [...listening.items, ...collections].sort((a, b) =>
23
+ (b.importedAt ?? "").localeCompare(a.importedAt ?? "") ||
24
+ (!a.importedAt && !b.importedAt ? (b.observedAt ?? "").localeCompare(a.observedAt ?? "") : 0));
25
+ const items = rows.slice(offset - start, offset - start + limit);
26
+ return { offset, total, items, nextOffset: offset + items.length < total ? offset + items.length : null,
27
+ ...(collectionState ? { collectionState } : {}) };
28
+ }
@@ -0,0 +1,16 @@
1
+ // Only the Library picker supplies a location. A handwritten @ name remains an ordinary mention.
2
+ export function libraryDraftLocation(value) {
3
+ const ref = value?.ref, label = value?.label;
4
+ if (typeof ref !== "string" || !ref || ref.length > 2048 || typeof label !== "string" || !label.trim() ||
5
+ label.length > 1024 || /[\u0000-\u001f\u007f]/u.test(ref + label)) return null;
6
+ return { ref, label };
7
+ }
8
+
9
+ export function hasLibraryDraftHeader(text, location) {
10
+ const header = `@${location.label}`;
11
+ return typeof text === "string" && (text === header || text.startsWith(`${header}\n`));
12
+ }
13
+
14
+ export function libraryDraftText(text, location) {
15
+ return !text || hasLibraryDraftHeader(text, location) ? text : `@${location.label}\n${text}`;
16
+ }
@@ -0,0 +1,12 @@
1
+ // Shelf names match the same way in the window and in the host's library tools.
2
+ export function matchLibraryNames(query) {
3
+ const fold = (value) => String(value ?? "").normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().trim();
4
+ const wanted = fold(query);
5
+ return (...names) => !wanted || names.some((name) => fold(name).includes(wanted));
6
+ }
7
+
8
+ // A player with no recording ID can only identify the displayed title, credit and album.
9
+ export function namedLibraryRecording(entry) {
10
+ const labels = [entry.title, entry.artist_credit, entry.album].map(text => String(text ?? "").trim().normalize("NFC"));
11
+ return `named:${JSON.stringify(labels)}`;
12
+ }