@audiofool/moondog 0.4.0-beta.2 → 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 (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -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 +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  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 +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -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/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. 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,12 @@ 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;
1327
+ }
1328
+
1329
+ recordSuggestionOutcome(outcome) {
1330
+ return this.#listeningHistoryStore?.recordSuggestionOutcome?.(outcome) ?? null;
1306
1331
  }
1307
1332
 
1308
1333
  moondogSuggestionHistory(tracks) {
@@ -1315,7 +1340,7 @@ export class AppleProjectionDomainServices {
1315
1340
  const slots = this.#listeningHistoryStore?.listeningMix?.({ subjectId: this.#subjectId, tracks }) ??
1316
1341
  tracks.map(() => "unknown");
1317
1342
  return slots.map((slot, index) => {
1318
- if (!["new", "known_artist", "unknown"].includes(slot)) return slot;
1343
+ if (slot === "familiar" || slot === "returning") return slot;
1319
1344
  const plays = this.#libraryPlayCount(tracks[index]);
1320
1345
  return plays >= 3 ? "familiar" : plays > 0 ? "heard" : slot;
1321
1346
  });
@@ -1828,7 +1853,7 @@ export class AppleProjectionDomainServices {
1828
1853
  return normalizeAppleCorrectionLabels({ listener_assertions: { avoids } }, this.#projection)
1829
1854
  .listener_assertions.avoids;
1830
1855
  });
1831
- return tracks.filter((track) => !gate.avoidsTrack(track));
1856
+ return allowedDiscoveryTracks(gate, tracks, this.#listeningHistoryStore, this.#subjectId);
1832
1857
  }
1833
1858
 
1834
1859
  // Choices live with the listening history, so a library alone cannot save them.
@@ -1841,6 +1866,16 @@ export class AppleProjectionDomainServices {
1841
1866
  return recordListenerChoice(this.#listeningHistoryStore, { ...choice, subjectId: this.#subjectId });
1842
1867
  }
1843
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
+
1844
1879
  // The choices in force, cheap enough to read when there is no saved reading.
1845
1880
  listenerChoices() {
1846
1881
  const store = this.#listeningHistoryStore;
@@ -1850,7 +1885,7 @@ export class AppleProjectionDomainServices {
1850
1885
  }
1851
1886
 
1852
1887
  isKnownDiscoveryTrack(track) {
1853
- return (this.#listeningHistoryStore?.listenedTracks?.({ subjectId: this.#subjectId }) ?? []).some(heard => exactTitleArtistMatch(track, heard));
1888
+ return isHeardMixSlot(this.listeningMix([track])[0]);
1854
1889
  }
1855
1890
 
1856
1891
  // Every Avoid in force, imported bans included, as the play paths read them.
@@ -1888,7 +1923,8 @@ export class AppleProjectionDomainServices {
1888
1923
  const accepted = [];
1889
1924
  let excludedLibraryMatches = 0;
1890
1925
  const allowed = this.filterDiscoveryTracks(prepared);
1891
- for (const track of allowed) {
1926
+ const historySlots = this.#listeningHistoryStore?.listeningMix?.({ subjectId: this.#subjectId, tracks: allowed });
1927
+ for (const [index, track] of allowed.entries()) {
1892
1928
  const query = Array.from(track.title).slice(0, 256).join("");
1893
1929
  const libraryResults = this.#projection.searchLibrary({
1894
1930
  query,
@@ -1904,7 +1940,8 @@ export class AppleProjectionDomainServices {
1904
1940
  const libraryMatch = libraryResults.tracks
1905
1941
  .map(safeTrack)
1906
1942
  .some((candidate) => exactTitleArtistMatch(track, candidate));
1907
- if (excludeKnown && libraryMatch) {
1943
+ const heard = isHeardMixSlot(historySlots?.[index]);
1944
+ if (excludeKnown && (libraryMatch || heard)) {
1908
1945
  excludedLibraryMatches += 1;
1909
1946
  continue;
1910
1947
  }
@@ -1912,7 +1949,7 @@ export class AppleProjectionDomainServices {
1912
1949
  ...track,
1913
1950
  knownness: {
1914
1951
  imported_library: libraryMatch ? "found_by_exact_title_artist" : "not_found_by_exact_title_artist",
1915
- listening_history: "not_checked",
1952
+ listening_history: historySlots ? (heard ? "found_by_exact_title_artist" : "not_found_by_exact_title_artist") : "not_checked",
1916
1953
  },
1917
1954
  });
1918
1955
  }
@@ -2057,6 +2094,7 @@ export class AppleProjectionDomainServices {
2057
2094
  return exploreProfileCatalog({
2058
2095
  listening,
2059
2096
  apple: this.#appleProfileCatalog(listening?.sections.listener_avoids), input,
2097
+ resolveChoice: appleCorrectionLabelResolver(this.#projection),
2060
2098
  });
2061
2099
  }
2062
2100
 
@@ -2069,11 +2107,11 @@ export class AppleProjectionDomainServices {
2069
2107
  return this.#listeningHistoryStore.listenerProfileStorage({ subjectId: this.#subjectId });
2070
2108
  }
2071
2109
 
2072
- getProfileBuildContext() {
2110
+ getProfileBuildContext(readingThrough = null) {
2073
2111
  const appleDigest = this.#projection.logicalDigest();
2074
2112
  const version = `${appleDigest}:${listeningVersion(this.#listeningHistoryStore)}`;
2075
- if (this.#profileBuildInput?.version !== version) {
2076
- 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 });
2077
2115
  const normalized = normalizeAppleCorrectionLabels({ listener_assertions: {
2078
2116
  preferences: listening.sections.listener_preferences, avoids: listening.sections.listener_avoids,
2079
2117
  } }, this.#projection).listener_assertions;
@@ -2083,13 +2121,13 @@ export class AppleProjectionDomainServices {
2083
2121
  subjectId: this.#subjectId,
2084
2122
  evidenceRevision: [appleDigest,
2085
2123
  this.#listeningHistoryStore.profileEvidenceRevision({ subjectId: this.#subjectId })],
2086
- listening, apple: this.#appleProfileCatalog(listening.sections.listener_avoids),
2124
+ listening, apple: this.#appleProfileCatalog(listening.sections.listener_avoids), appleRevision: appleDigest,
2087
2125
  }) };
2088
2126
  }
2089
2127
  return { store: this.getListenerProfileStore(), input: this.#profileBuildInput.input };
2090
2128
  }
2091
2129
 
2092
- async getProfileSummary(argumentsValue) {
2130
+ async getProfileSummary(argumentsValue, { includeReviewTracks = false } = {}) {
2093
2131
  const input = modelArguments(argumentsValue, new Set(["maxItems"]));
2094
2132
  const bounded = boundedLimit(
2095
2133
  input.maxItems,
@@ -2140,26 +2178,7 @@ export class AppleProjectionDomainServices {
2140
2178
  signal: `You explicitly said you like this ${item.entity_type}`,
2141
2179
  evidence_id: item.evidence_id,
2142
2180
  }));
2143
- const spotifyStrongPreferences = listening
2144
- ? listening.curated_preferences.saved_tracks
2145
- .filter(
2146
- (item) =>
2147
- !listenerAssertionAvoids(
2148
- listening,
2149
- "track",
2150
- item.label,
2151
- item.artist_credit,
2152
- ),
2153
- )
2154
- .map((item) => ({
2155
- label: item.label,
2156
- entity_type: "track",
2157
- artist_credit: item.artist_credit,
2158
- track_ref_id: item.track_ref_id,
2159
- signal: `Saved in ${item.source_label ?? "Spotify"} library`,
2160
- evidence_id: item.evidence_id,
2161
- }))
2162
- : [];
2181
+ const curatedStrongPreferences = curatedPreferenceItems(listening, listenerAssertionAvoids);
2163
2182
  const appleFamiliarity = familiarityItems.map((item) => {
2164
2183
  const playCount = item.observation_summary?.play_count;
2165
2184
  const result = {
@@ -2221,15 +2240,11 @@ export class AppleProjectionDomainServices {
2221
2240
  return {
2222
2241
  profile_version: listening ? "profile-projection/1" : raw.schema_version,
2223
2242
  max_items_applied: bounded,
2224
- strong_preferences: interleaveUnique(
2225
- [
2226
- listenerStrongPreferences,
2227
- appleStrongPreferences,
2228
- spotifyStrongPreferences,
2229
- ],
2230
- bounded,
2231
- (item) => JSON.stringify([item.entity_type, item.label, item.artist_credit ?? ""]),
2232
- ),
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),
2233
2248
  familiarity: interleaveUnique(
2234
2249
  [appleFamiliarity, spotifyFamiliarity],
2235
2250
  bounded,
@@ -2256,6 +2271,7 @@ export class AppleProjectionDomainServices {
2256
2271
  listening.coverage.effective_listening_events,
2257
2272
  profiled_listening_events:
2258
2273
  listening.coverage.profiled_listening_events,
2274
+ events_with_played_duration: listening.coverage.events_with_played_duration,
2259
2275
  listening_hours: listening.coverage.listening_hours,
2260
2276
  listening_tracks: listening.coverage.distinct_tracks,
2261
2277
  resolved_listening_tracks: listening.coverage.resolved_tracks,
@@ -2470,10 +2486,9 @@ export class AppleProjectionDomainServices {
2470
2486
  "The playlist track count does not match the explicit user intent.",
2471
2487
  );
2472
2488
  }
2473
- const external = selections.map((selection) => trustedTracks.get(selection.trackRefId))
2474
- .filter((track) => track.candidate_scope === "external_catalog");
2475
- if (this.filterDiscoveryTracks(external).length !== external.length) {
2476
- 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.");
2477
2492
  }
2478
2493
  const tracks = selections.map((selection, index) => {
2479
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
+ }