krillplayer-plugin 0.1.0 → 0.2.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 (43) hide show
  1. package/README.md +5 -0
  2. package/dist/cli.js +949 -636
  3. package/package.json +3 -2
  4. package/skill/krillplayer-plugin/SKILL.md +2 -1
  5. package/skill/krillplayer-plugin/assets/samples/file-share/plugin.ts +1 -20
  6. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-connect.json +23 -0
  7. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-decode.json +19 -0
  8. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-content-rejected.json +31 -0
  9. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-login-expired.json +31 -0
  10. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-muted.json +31 -0
  11. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-not-logged-in.json +14 -0
  12. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-other.json +31 -0
  13. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-rate-limited.json +31 -0
  14. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-sent.json +28 -0
  15. package/skill/krillplayer-plugin/assets/samples/live-video-platform/manifest.ts +2 -1
  16. package/skill/krillplayer-plugin/assets/samples/live-video-platform/plugin.ts +40 -1
  17. package/skill/krillplayer-plugin/assets/samples/media-server/plugin.ts +1 -35
  18. package/skill/krillplayer-plugin/assets/samples/network-share/plugin.ts +1 -20
  19. package/skill/krillplayer-plugin/references/choosing-a-kind.md +2 -2
  20. package/skill/krillplayer-plugin/references/contract.d.ts +80 -112
  21. package/skill/krillplayer-plugin/references/errors-and-fixes.md +1 -1
  22. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-empty-folder.json +0 -11
  23. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-gone-not-found.json +0 -12
  24. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-lists-subfolders-and-media.json +0 -28
  25. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-second-page.json +0 -22
  26. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-skips-subtitles.json +0 -21
  27. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-root-first-page.json +0 -25
  28. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-root-second-page.json +0 -22
  29. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-everything-first-page.json +0 -74
  30. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-everything-last-page.json +0 -86
  31. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-nothing-new.json +0 -12
  32. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-since-a-token-with-a-removal.json +0 -88
  33. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-ids-first-page.json +0 -15
  34. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-ids-last-page.json +0 -14
  35. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-empty-folder.json +0 -60
  36. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-gives-size-and-modified-time.json +0 -78
  37. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-gone-not-found.json +0 -60
  38. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-second-page.json +0 -71
  39. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-a-range.json +0 -62
  40. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-an-info-file.json +0 -62
  41. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-file-gone-not-found.json +0 -62
  42. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-root.json +0 -84
  43. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-source-offline-retryable.json +0 -61
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- // plugins/package/cli.ts
1
+ // package/cli.ts
2
2
  import { execFile as execFile2 } from "node:child_process";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { cp, mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir5, readFile as readFile6, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
@@ -8,7 +8,7 @@ import { basename as basename2, dirname as dirname2, join as join5, relative as
8
8
  import { fileURLToPath as fileURLToPath3 } from "node:url";
9
9
  import { parseArgs, promisify as promisify2 } from "node:util";
10
10
 
11
- // plugins/contract/schema.ts
11
+ // contract/schema.ts
12
12
  var string = { kind: "string" };
13
13
  var integer = { kind: "integer" };
14
14
  var number = { kind: "number" };
@@ -17,8 +17,8 @@ var bytes = { kind: "bytes" };
17
17
  function constant(value) {
18
18
  return { kind: "constant", value };
19
19
  }
20
- function enumeration(name, values, unknown) {
21
- return { kind: "enum", name, values, ...unknown === void 0 ? {} : { unknown } };
20
+ function enumeration(name2, values, unknown) {
21
+ return { kind: "enum", name: name2, values, ...unknown === void 0 ? {} : { unknown } };
22
22
  }
23
23
  function array(of) {
24
24
  return { kind: "array", of };
@@ -29,21 +29,21 @@ function map(of) {
29
29
  function optional(of) {
30
30
  return { kind: "optional", of };
31
31
  }
32
- function object(name, fields, swift) {
33
- return { kind: "object", name, fields, ...swift === void 0 ? {} : { swift } };
32
+ function object(name2, fields, swift) {
33
+ return { kind: "object", name: name2, fields, ...swift === void 0 ? {} : { swift } };
34
34
  }
35
- function union(name, tag, variants, swift) {
35
+ function union(name2, tag, variants, swift) {
36
36
  const byValue = {};
37
37
  for (const variant of variants) {
38
38
  const value = variant.fields[tag].value;
39
- if (byValue[value] !== void 0) throw new Error(`union ${name} has two variants tagged ${value}`);
39
+ if (byValue[value] !== void 0) throw new Error(`union ${name2} has two variants tagged ${value}`);
40
40
  byValue[value] = variant;
41
41
  }
42
- return { kind: "union", name, tag, variants: byValue, wrapped: false, ...swift === void 0 ? {} : { swift } };
42
+ return { kind: "union", name: name2, tag, variants: byValue, wrapped: false, ...swift === void 0 ? {} : { swift } };
43
43
  }
44
- function wrapped(name, tag, variants) {
45
- if (tag in variants) throw new Error(`union ${name} cannot have a variant named like its tag ${tag}`);
46
- return { kind: "union", name, tag, variants, wrapped: true };
44
+ function wrapped(name2, tag, variants) {
45
+ if (tag in variants) throw new Error(`union ${name2} cannot have a variant named like its tag ${tag}`);
46
+ return { kind: "union", name: name2, tag, variants, wrapped: true };
47
47
  }
48
48
  var pages = /* @__PURE__ */ new Map();
49
49
  function paged(of) {
@@ -55,7 +55,7 @@ function paged(of) {
55
55
  return page;
56
56
  }
57
57
 
58
- // plugins/contract/contract.ts
58
+ // contract/contract.ts
59
59
  var CONTRACT = { interfaceLevel: 0, revision: 2 };
60
60
  var STORAGE_LIMITS = { keyBytes: 256, valueBytes: 64 * 1024, pluginBytes: 1024 * 1024 };
61
61
  var RUNTIME_LIMITS = { memoryBytes: 64 * 1024 * 1024, callSeconds: 20, stackBytes: 256 * 1024, callDepth: 64 };
@@ -69,7 +69,6 @@ var Capability = enumeration("Capability", [
69
69
  "music",
70
70
  "play",
71
71
  "resolve",
72
- "library",
73
72
  "resources",
74
73
  "subtitles",
75
74
  "subtitleSearch",
@@ -79,7 +78,8 @@ var Capability = enumeration("Capability", [
79
78
  "login",
80
79
  "playbackReport",
81
80
  "views",
82
- "libraryChanges"
81
+ "danmakuSend",
82
+ "browseLists"
83
83
  ]);
84
84
  var Media = enumeration("Media", ["video", "audio"]);
85
85
  var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
@@ -227,6 +227,8 @@ var Folder = object("Folder", { kind: constant("folder"), ...collectionBase });
227
227
  var Collection = union("Collection", "kind", [Series, Season, BoxSet, Playlist, Folder], "CollectionContent");
228
228
  var Entry = wrapped("Entry", "type", { item: Item, channel: Channel, collection: Collection });
229
229
  var PagedEntry = paged(Entry);
230
+ var BrowseListKind = enumeration("BrowseListKind", ["video", "live", "audio", "file"]);
231
+ var BrowseList = object("BrowseList", { id: string, title: string, kind: BrowseListKind });
230
232
  var ArtistRef = object("ArtistRef", { id: string, name: string, image: optional(string) });
231
233
  var albumRef = {
232
234
  id: string,
@@ -279,33 +281,6 @@ var Lyrics = object("Lyrics", {
279
281
  synced: boolean,
280
282
  lines: array(object("LyricsLine", { start: optional(number), end: optional(number), text: string, translation: optional(string) }))
281
283
  });
282
- var LibraryDirectory = object("LibraryDirectory", {
283
- type: constant("directory"),
284
- path: string,
285
- name: string,
286
- modified: optional(number),
287
- tag: optional(string)
288
- });
289
- var LibraryFile = object("LibraryFile", {
290
- type: constant("file"),
291
- path: string,
292
- name: string,
293
- itemId: string,
294
- media: Media,
295
- size: optional(integer),
296
- modified: optional(number),
297
- tag: optional(string)
298
- });
299
- var LibraryIdentified = object("LibraryIdentified", { type: constant("identified"), item: Item, series: optional(Series) });
300
- var LibraryEntry = union("LibraryEntry", "type", [LibraryDirectory, LibraryFile, LibraryIdentified]);
301
- var PagedLibraryEntry = paged(LibraryEntry);
302
- var LibraryChanges = object("LibraryChanges", {
303
- entries: array(LibraryEntry),
304
- removed: optional(array(string)),
305
- next: optional(string),
306
- since: string
307
- });
308
- var LibraryIds = object("LibraryIds", { ids: array(string), next: optional(string) });
309
284
  var FilesProtocol = enumeration("FilesProtocol", ["smb", "local"]);
310
285
  var FileEntry = object("FileEntry", {
311
286
  name: string,
@@ -342,7 +317,8 @@ var Parameter = object("Parameter", {
342
317
  options: optional(array(Option)),
343
318
  dynamicOptions: optional(boolean),
344
319
  dependsOn: optional(array(string)),
345
- visibleWhen: optional(array(object("ParameterCondition", { name: string, values: array(string) })))
320
+ visibleWhen: optional(array(object("ParameterCondition", { name: string, values: array(string) }))),
321
+ perSource: optional(boolean)
346
322
  });
347
323
  var Contributions = object("Contributions", {
348
324
  playerPanels: optional(array(object("PlayerPanelContribution", { id: string, title: string, kinds: array(ItemKind) }))),
@@ -367,6 +343,8 @@ var PluginManifest = object("PluginManifest", {
367
343
  hosts: array(string),
368
344
  userProvidedURLs: optional(boolean),
369
345
  readsCredentials: optional(boolean),
346
+ loginRequired: optional(boolean),
347
+ singleSource: optional(boolean),
370
348
  // 图片地址里不参与缓存键的查询参数名(不分大小写),例如每次都换的令牌与盐(ADR 0015「图片」)。尺寸参数内核另外固定去掉,不用写。
371
349
  imageCacheIgnoredParameters: optional(array(string)),
372
350
  // 要用 krillplayer.files 时写哪种协议(contract.md 6.1)。连哪台主机、哪个共享、用什么账号由内核向用户要,不写在 parameters 里,插件也读不到。
@@ -389,6 +367,9 @@ var PluginErrorKind = enumeration("PluginErrorKind", [
389
367
  "refused",
390
368
  "retryable",
391
369
  "notFound",
370
+ "muted",
371
+ "rateLimited",
372
+ "contentRejected",
392
373
  "other"
393
374
  ], "other");
394
375
  var PluginError = object("PluginError", {
@@ -437,27 +418,20 @@ var Playable = object("Playable", {
437
418
  // 这一路的原始文件名,给字幕插件与弹幕插件匹配用(contract.md 3.1);不给时内核用条目的文件名或标题。
438
419
  filename: optional(string)
439
420
  });
440
- var PageLink = object("PageLink", {
441
- page: string,
442
- title: optional(string),
443
- values: optional(map(string))
444
- });
445
421
  var Card = object("Card", {
446
- kind: enumeration("CardKind", ["entry", "link", "banner", "comment"]),
422
+ kind: enumeration("CardKind", ["entry", "comment"]),
447
423
  title: string,
448
424
  subtitle: optional(string),
449
425
  caption: optional(string),
450
426
  image: optional(string),
451
427
  text: optional(string),
452
428
  time: optional(number),
453
- entry: optional(Entry),
454
- open: optional(PageLink)
429
+ entry: optional(Entry)
455
430
  });
456
431
  var Section = object("Section", {
457
- layout: enumeration("SectionLayout", ["row", "grid", "list", "banners"]),
432
+ layout: enumeration("SectionLayout", ["row", "grid", "list"]),
458
433
  title: optional(string),
459
- cards: array(Card),
460
- more: optional(PageLink)
434
+ cards: array(Card)
461
435
  });
462
436
  var ComponentPage = object("ComponentPage", {
463
437
  title: optional(string),
@@ -468,7 +442,6 @@ var ComponentPage = object("ComponentPage", {
468
442
  empty: optional(string)
469
443
  }, "PageContent");
470
444
  var ActionResult = object("ActionResult", {
471
- open: optional(PageLink),
472
445
  message: optional(string)
473
446
  });
474
447
  var ChannelStatus = object("ChannelStatus", {
@@ -640,7 +613,7 @@ var RSSFeed = object("RSSFeed", {
640
613
  episodes: array(RSSEpisode)
641
614
  });
642
615
  var WorkKind = enumeration("WorkKind", ["movie", "series"]);
643
- var ListName = enumeration("ListName", ["trending", "popular", "topRated", "upcoming", "onAir"]);
616
+ var ListName = enumeration("ListName", ["trending", "popular", "topRated", "upcoming", "nowPlaying", "onAir"]);
644
617
  var Genre = enumeration("Genre", [
645
618
  "action",
646
619
  "adventure",
@@ -666,6 +639,21 @@ var Genre = enumeration("Genre", [
666
639
  "war",
667
640
  "western"
668
641
  ]);
642
+ var Network = enumeration("Network", [
643
+ "netflix",
644
+ "hbo",
645
+ "disneyPlus",
646
+ "appleTv",
647
+ "primeVideo",
648
+ "hulu",
649
+ "peacock",
650
+ "paramountPlus",
651
+ "iqiyi",
652
+ "tencentVideo",
653
+ "youku",
654
+ "bilibili",
655
+ "mangoTv"
656
+ ]);
669
657
  var Work = object("Work", {
670
658
  kind: WorkKind,
671
659
  ids: Ids,
@@ -679,6 +667,7 @@ var PagedWork = paged(Work);
679
667
  var MetadataSearchOptions = object("MetadataSearchOptions", { year: optional(integer), cursor: optional(string) });
680
668
  var MetadataListOptions = object("MetadataListOptions", {
681
669
  genre: optional(Genre),
670
+ network: optional(Network),
682
671
  country: optional(string),
683
672
  year: optional(integer),
684
673
  cursor: optional(string)
@@ -763,11 +752,14 @@ var CryptoKey = object("CryptoKey", {
763
752
  });
764
753
  var CryptoKeyPair = object("CryptoKeyPair", { publicKey: CryptoKey, privateKey: CryptoKey });
765
754
  var SLOT_RULES = {
755
+ // 导出 lists 的是具名列表(contract.md 2.1),list、parameters、options 都按列表的 id 问,能力是 browseLists 而不是 browse:
756
+ // 只认 browse 的旧内核不会按一份列表的老样子去调它,不认识的 browseLists 跳过。没导出 lists 的是只有一份列表的特例。
766
757
  browse: {
767
- functions: ["parameters", "options", "list", "search", "channel", "collection", "schedule"],
758
+ functions: ["lists", "parameters", "options", "list", "search", "channel", "collection", "schedule"],
768
759
  required: ["list"],
769
760
  pairs: [],
770
- capabilities: { browse: ["list"] }
761
+ capabilities: { browse: ["list"], browseLists: ["lists"] },
762
+ supersedes: { browseLists: "browse" }
771
763
  },
772
764
  // 没有音乐内容的实例 sections 返回空数组,内核就不在音乐里显示它(contract.md 2.2)。
773
765
  music: {
@@ -777,14 +769,6 @@ var SLOT_RULES = {
777
769
  capabilities: { music: ["sections"] }
778
770
  },
779
771
  play: { functions: ["start"], required: ["start"], pairs: [], capabilities: { play: ["start"] } },
780
- // 文件类来源导出 list(与可选的 read),媒体服务器导出 changes 与 ids(contract.md 2.10)。两样能力分开:只认 library 的旧内核
781
- // 见到只导出 changes 的插件时不会去调它没有的 list,不认识的 libraryChanges 跳过。
782
- library: {
783
- functions: ["list", "read", "changes", "ids"],
784
- required: [],
785
- pairs: [["changes", "ids"]],
786
- capabilities: { library: ["list"], libraryChanges: ["changes"] }
787
- },
788
772
  // 资源插件(contract.md 2.5):按作品回答有没有可播的版本。
789
773
  resources: { functions: ["find"], required: ["find"], pairs: [], capabilities: { resources: ["find"] } },
790
774
  // 只导出 search 的是字幕插件,不是自带字幕的来源(contract.md 第 2 节)。
@@ -794,11 +778,12 @@ var SLOT_RULES = {
794
778
  pairs: [],
795
779
  capabilities: { subtitles: ["list"], subtitleSearch: ["search"] }
796
780
  },
781
+ // send 是在直播间里发一条弹幕(contract.md 2.7),单独一项能力:只认 danmaku 的旧内核不认识 danmakuSend,跳过,不会去调它。
797
782
  danmaku: {
798
- functions: ["connect", "decode", "segment", "match", "comments"],
783
+ functions: ["connect", "decode", "segment", "match", "comments", "send"],
799
784
  required: [],
800
785
  pairs: [["connect", "decode"], ["match", "comments"]],
801
- capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"] }
786
+ capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"], danmakuSend: ["send"] }
802
787
  },
803
788
  status: { functions: ["check", "images"], required: ["check"], pairs: [], capabilities: { status: ["check"] } },
804
789
  login: {
@@ -808,12 +793,14 @@ var SLOT_RULES = {
808
793
  capabilities: { login: ["methods"] }
809
794
  },
810
795
  playbackReport: { functions: ["report"], required: ["report"], pairs: [], capabilities: { playbackReport: ["report"] } },
811
- views: { functions: ["page", "panel", "action"], required: ["page"], pairs: [], capabilities: { views: ["page"] } },
796
+ // 组件页面 page 去掉了(ADR 0040),剩下播放器面板与卡片操作。
797
+ views: { functions: ["panel", "action"], required: [], pairs: [], capabilities: { views: ["panel", "action"] } },
812
798
  // 顶层的 parameters 不算能力(contract.md 第 2 节)。
813
799
  parameters: { functions: ["options"], required: ["options"], pairs: [], capabilities: {} }
814
800
  };
815
801
  var SLOT_RETURNS = {
816
802
  browse: {
803
+ lists: { schema: array(BrowseList) },
817
804
  parameters: { schema: array(Parameter) },
818
805
  options: { schema: array(Option) },
819
806
  list: { schema: PagedEntry },
@@ -834,7 +821,6 @@ var SLOT_RETURNS = {
834
821
  lyrics: { schema: Lyrics, nullable: true }
835
822
  },
836
823
  play: { start: { schema: Playable } },
837
- library: { list: { schema: PagedLibraryEntry }, read: { schema: bytes }, changes: { schema: LibraryChanges }, ids: { schema: LibraryIds } },
838
824
  resources: { find: { schema: array(ResourceVersion) } },
839
825
  subtitles: { list: { schema: array(SubtitleTrack) }, search: { schema: array(SubtitleTrack) }, fetch: { schema: Subtitle } },
840
826
  danmaku: {
@@ -851,24 +837,24 @@ var SLOT_RETURNS = {
851
837
  poll: { schema: LoginPoll },
852
838
  account: { schema: LoginAccount, nullable: true }
853
839
  },
854
- views: { page: { schema: ComponentPage }, panel: { schema: ComponentPage }, action: { schema: ActionResult } },
840
+ views: { panel: { schema: ComponentPage }, action: { schema: ActionResult } },
855
841
  parameters: { options: { schema: array(Option) } },
856
842
  resolve: { "": { schema: Resolved, nullable: true } }
857
843
  };
858
844
  var TOP_LEVEL_FUNCTIONS = { resolve: "resolve" };
859
- function slotMember(slot, name) {
845
+ function slotMember(slot, name2) {
860
846
  if (typeof slot !== "object" && typeof slot !== "function" || slot === null) return void 0;
861
- const descriptor = Object.getOwnPropertyDescriptor(slot, name);
847
+ const descriptor = Object.getOwnPropertyDescriptor(slot, name2);
862
848
  return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
863
849
  }
864
850
 
865
- // plugins/packer/pack.ts
851
+ // packer/pack.ts
866
852
  import { build as build2 } from "esbuild";
867
853
  import { mkdir as mkdir2, readdir as readdir4, readFile as readFile5, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
868
854
  import { join as join4 } from "node:path";
869
855
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
870
856
 
871
- // plugins/contract/not-yet-used.ts
857
+ // contract/not-yet-used.ts
872
858
  var NOT_YET_USED = [
873
859
  "Album.compilation",
874
860
  "Album.count",
@@ -886,19 +872,10 @@ var NOT_YET_USED = [
886
872
  "ArtistPage.artist",
887
873
  "ArtistRef.image",
888
874
  "BoxSet.ancestors",
889
- "ChannelImage.id",
890
- "ChannelImage.image",
875
+ "BoxSet.ids",
891
876
  "ChannelRef.image",
892
877
  "ChannelRef.kind",
893
- "ChannelStatus.id",
894
878
  "ChannelStatus.latest",
895
- "ChannelStatus.live",
896
- "ChannelStatus.liveId",
897
- "ChannelStatus.offlineReason",
898
- "ChannelStatus.retryAfter",
899
- "ChannelStatus.session",
900
- "ChannelStatus.title",
901
- "ChannelStatus.unknownReason",
902
879
  "CollectionRef.kind",
903
880
  "CommentGift.count",
904
881
  "CommentGift.name",
@@ -953,15 +930,13 @@ var NOT_YET_USED = [
953
930
  "Podcast.order",
954
931
  "Podcast.summary",
955
932
  "PodcastEpisode.episodeType",
956
- "PodcastEpisode.index",
957
- "PodcastEpisode.published",
958
- "PodcastEpisode.season",
959
933
  "PodcastEpisode.summary",
960
934
  "ResolvedBrowse.entry",
961
935
  "ScheduleEntry.id",
962
936
  "ScheduleEntry.image",
963
937
  "ScheduleEntry.summary",
964
938
  "Season.ancestors",
939
+ "Season.ids",
965
940
  "Series.ancestors",
966
941
  "Song.disc",
967
942
  "Song.index",
@@ -975,12 +950,10 @@ var NOT_YET_USED = [
975
950
  "VersionInfo.bitDepth",
976
951
  "VersionInfo.languages",
977
952
  "VersionInfo.sampleRate",
978
- "resolve",
979
- "status.check",
980
- "status.images"
953
+ "resolve"
981
954
  ];
982
955
 
983
- // plugins/host/i18n.ts
956
+ // host/i18n.ts
984
957
  var DICTIONARY_BYTES = 256 * 1024;
985
958
  function parseTag(text) {
986
959
  const parts = text.replaceAll("_", "-").split("-");
@@ -1048,9 +1021,9 @@ function pieces(template) {
1048
1021
  }
1049
1022
  if (character === "{") {
1050
1023
  const end = template.indexOf("}", index + 1);
1051
- const name = end < 0 ? "" : template.slice(index + 1, end);
1052
- if (name !== "" && !name.includes("{")) {
1053
- result.push({ text: literal }, { name });
1024
+ const name2 = end < 0 ? "" : template.slice(index + 1, end);
1025
+ if (name2 !== "" && !name2.includes("{")) {
1026
+ result.push({ text: literal }, { name: name2 });
1054
1027
  literal = "";
1055
1028
  index = end;
1056
1029
  continue;
@@ -1086,11 +1059,11 @@ function translate({ locale, language, dictionaries: dictionaries2 }, text, valu
1086
1059
  return fill(lookup(dictionaries2, locale, language, text, context), values, locale);
1087
1060
  }
1088
1061
 
1089
- // plugins/trial-runner/trial.ts
1062
+ // trial-runner/trial.ts
1090
1063
  import { readdir as readdir3, readFile as readFile4, writeFile } from "node:fs/promises";
1091
1064
  import { basename, join as join3, resolve } from "node:path";
1092
1065
 
1093
- // plugins/host/files.ts
1066
+ // host/files.ts
1094
1067
  var FileServiceError = class extends Error {
1095
1068
  failure;
1096
1069
  constructor(failure2) {
@@ -1166,7 +1139,7 @@ function createFiles(host) {
1166
1139
  };
1167
1140
  }
1168
1141
 
1169
- // plugins/host/network.ts
1142
+ // host/network.ts
1170
1143
  var MAX_REDIRECTS = 20;
1171
1144
  var REMEMBERED_HOSTS = 8;
1172
1145
  var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -1175,6 +1148,18 @@ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "pr
1175
1148
  function carries(text, secret) {
1176
1149
  return text.includes(secret) || text.includes("%") && percentDecoded(text).includes(secret);
1177
1150
  }
1151
+ var TOKEN_MINIMUM_LENGTH = 16;
1152
+ function looksLikeToken(secret) {
1153
+ const scalars = [...secret];
1154
+ if (scalars.length < TOKEN_MINIMUM_LENGTH) return false;
1155
+ const classes = /* @__PURE__ */ new Set();
1156
+ for (const scalar of scalars) {
1157
+ const code = scalar.codePointAt(0) ?? 0;
1158
+ classes.add(code >= 48 && code <= 57 ? 0 : code >= 97 && code <= 122 ? 1 : code >= 65 && code <= 90 ? 2 : 3);
1159
+ if (classes.size >= 2) return true;
1160
+ }
1161
+ return false;
1162
+ }
1178
1163
  function percentDecoded(text) {
1179
1164
  const input = new TextEncoder().encode(text);
1180
1165
  const bytes2 = [];
@@ -1257,9 +1242,9 @@ function restrictedAddress(address, sharedSpace = false) {
1257
1242
  return (v6[0] & 254) === 252 || v6[0] === 254 && (v6[1] & 192) === 128;
1258
1243
  }
1259
1244
  function localHost(host, sharedSpace = false) {
1260
- const name = bareHost(host);
1261
- if (name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local")) return true;
1262
- return restrictedAddress(name, sharedSpace);
1245
+ const name2 = bareHost(host);
1246
+ if (name2 === "localhost" || name2.endsWith(".localhost") || name2.endsWith(".local")) return true;
1247
+ return restrictedAddress(name2, sharedSpace);
1263
1248
  }
1264
1249
  function parseIPv4(text) {
1265
1250
  const parts = text.split(".");
@@ -1339,6 +1324,8 @@ var Chain = class {
1339
1324
  once;
1340
1325
  remembered;
1341
1326
  secrets;
1327
+ // `derived-no-secrets` 查的那部分:像令牌的值(`looksLikeToken`)。删减请求头仍按全部凭证值。
1328
+ tokens;
1342
1329
  use;
1343
1330
  grants;
1344
1331
  startsAtUserAddress = false;
@@ -1355,6 +1342,7 @@ var Chain = class {
1355
1342
  this.once = lower(grants.once);
1356
1343
  this.remembered = grants.remembered ?? {};
1357
1344
  this.secrets = (grants.secrets ?? []).filter((secret) => secret !== "");
1345
+ this.tokens = this.secrets.filter(looksLikeToken);
1358
1346
  }
1359
1347
  classify(host) {
1360
1348
  return this.user.has(host) ? "user" : this.declared.has(host) ? "declared" : "derived";
@@ -1375,8 +1363,8 @@ var Chain = class {
1375
1363
  throw this.refuse("login-page", address, `${this.label(address)} is not declared in the plugin manifest`);
1376
1364
  }
1377
1365
  this.startsAtUserAddress = (this.grants.userAddresses ?? []).some((value) => normalForm(value)?.href === address.href);
1378
- const headers = remembered ? only(request.headers ?? {}, SAFELIST) : { ...request.headers };
1379
- return this.settle({ address, hostClass, method, headers, body: request.body === true, frames: request.frames });
1366
+ const headers2 = remembered ? only(request.headers ?? {}, SAFELIST) : { ...request.headers };
1367
+ return this.settle({ address, hostClass, method, headers: headers2, body: request.body === true, frames: request.frames });
1380
1368
  }
1381
1369
  // 上一跳回了跳转。方法、请求体、请求头按上一跳的状态码与两跳的关系改写。
1382
1370
  redirect(status, location) {
@@ -1389,7 +1377,7 @@ var Chain = class {
1389
1377
  const becomesGet = status === 303 ? previous.method !== "GET" && previous.method !== "HEAD" : (status === 301 || status === 302) && previous.method === "POST";
1390
1378
  const method = becomesGet ? "GET" : previous.method;
1391
1379
  const body = becomesGet ? false : previous.body;
1392
- let headers = becomesGet ? without(previous.headers, BODY_HEADERS) : previous.headers;
1380
+ let headers2 = becomesGet ? without(previous.headers, BODY_HEADERS) : previous.headers;
1393
1381
  if (this.seen.has(`${method} ${address.href}`)) throw this.refuse("redirect-loop", address, `redirect loop at ${this.label(address)}`);
1394
1382
  const downgrade = previous.address.scheme === "https" && address.scheme === "http";
1395
1383
  if (downgrade && this.use !== "playback-follow" && this.use !== "playback-probe") {
@@ -1403,9 +1391,9 @@ var Chain = class {
1403
1391
  const upgrade = hostClass === "user" && address.host === previous.address.host && previous.address.scheme === "http" && address.scheme === "https";
1404
1392
  if (this.leftOrigin || address.origin !== previous.address.origin && !upgrade) {
1405
1393
  this.leftOrigin = true;
1406
- headers = hostClass === "derived" ? only(headers, SAFELIST) : this.withoutCredentials(headers);
1394
+ headers2 = hostClass === "derived" ? only(headers2, SAFELIST) : this.withoutCredentials(headers2);
1407
1395
  }
1408
- return this.settle({ address, hostClass, method, headers, body });
1396
+ return this.settle({ address, hostClass, method, headers: headers2, body });
1409
1397
  }
1410
1398
  // 主机解析出的地址。解析不出(空)算连不上,不是这里的事。
1411
1399
  resolved(addresses) {
@@ -1488,7 +1476,7 @@ var Chain = class {
1488
1476
  return "only network stream addresses are allowed";
1489
1477
  }
1490
1478
  }
1491
- settle({ address, hostClass, method, headers, body, frames }) {
1479
+ settle({ address, hostClass, method, headers: headers2, body, frames }) {
1492
1480
  if (hostClass === "derived") {
1493
1481
  if (method !== "GET" && method !== "HEAD" || body) {
1494
1482
  throw this.refuse(
@@ -1497,14 +1485,14 @@ var Chain = class {
1497
1485
  `${address.host} is neither declared nor given by the user, so only GET and HEAD without a body may be sent to it`
1498
1486
  );
1499
1487
  }
1500
- const carried = [address.href, ...Object.keys(headers), ...Object.values(headers), ...frames ?? []];
1501
- if (this.secrets.some((secret) => carried.some((text) => carries(text, secret)))) {
1488
+ const carried = [address.href, ...Object.keys(headers2), ...Object.values(headers2), ...frames ?? []];
1489
+ if (this.tokens.some((secret) => carried.some((text) => carries(text, secret)))) {
1502
1490
  throw this.refuse("derived-no-secrets", address, `credentials may not be sent to ${address.host}, a host that is neither declared nor given by the user`);
1503
1491
  }
1504
1492
  }
1505
1493
  const publicOnly = this.publicOnly(hostClass);
1506
1494
  if (publicOnly !== null && localHost(address.host, publicOnly.sharedSpace)) throw this.privateAddress(address, "is");
1507
- const pass = { hostClass, address, method, headers, body, challenge: !this.leftOrigin, publicOnly };
1495
+ const pass = { hostClass, address, method, headers: headers2, body, challenge: !this.leftOrigin, publicOnly };
1508
1496
  this.seen.add(`${method} ${address.href}`);
1509
1497
  this.current = pass;
1510
1498
  return pass;
@@ -1518,15 +1506,15 @@ var Chain = class {
1518
1506
  privateAddress(address, verb = "resolves to") {
1519
1507
  return this.refuse("public-address", address, `${this.label(address)} ${verb} a private, loopback or link-local address`);
1520
1508
  }
1521
- withoutCredentials(headers) {
1522
- return Object.fromEntries(Object.entries(headers).filter(([name, value]) => !CREDENTIAL_HEADERS.has(name.toLowerCase()) && !this.secrets.some((secret) => carries(name, secret) || carries(value, secret))));
1509
+ withoutCredentials(headers2) {
1510
+ return Object.fromEntries(Object.entries(headers2).filter(([name2, value]) => !CREDENTIAL_HEADERS.has(name2.toLowerCase()) && !this.secrets.some((secret) => carries(name2, secret) || carries(value, secret))));
1523
1511
  }
1524
1512
  refuse(rule, address, message) {
1525
1513
  return new NetworkRefusal(PREFIX[this.use], rule, address.host, message);
1526
1514
  }
1527
1515
  };
1528
- var only = (headers, names) => Object.fromEntries(Object.entries(headers).filter(([name]) => names.has(name.toLowerCase())));
1529
- var without = (headers, names) => Object.fromEntries(Object.entries(headers).filter(([name]) => !names.has(name.toLowerCase())));
1516
+ var only = (headers2, names) => Object.fromEntries(Object.entries(headers2).filter(([name2]) => names.has(name2.toLowerCase())));
1517
+ var without = (headers2, names) => Object.fromEntries(Object.entries(headers2).filter(([name2]) => !names.has(name2.toLowerCase())));
1530
1518
  function imageAddress(text, userHosts) {
1531
1519
  const address = normalForm(text);
1532
1520
  if (address === null || address.scheme !== "http" && address.scheme !== "https") return null;
@@ -1537,7 +1525,7 @@ function imageAddress(text, userHosts) {
1537
1525
  return url.href;
1538
1526
  }
1539
1527
 
1540
- // plugins/host/formats.ts
1528
+ // host/formats.ts
1541
1529
  var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r";
1542
1530
  function trimSpace(text) {
1543
1531
  let start = 0;
@@ -1555,9 +1543,9 @@ function textOf(data) {
1555
1543
  var NAMED_ENTITIES = /* @__PURE__ */ new Map([["lt", "<"], ["gt", ">"], ["amp", "&"], ["quot", '"'], ["apos", "'"]]);
1556
1544
  function decodeEntities(text) {
1557
1545
  if (!text.includes("&")) return text;
1558
- return text.replace(/&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,8}|[A-Za-z][A-Za-z0-9]{0,31});/g, (whole, name) => {
1559
- if (name[0] !== "#") return NAMED_ENTITIES.get(name) ?? whole;
1560
- const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
1546
+ return text.replace(/&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,8}|[A-Za-z][A-Za-z0-9]{0,31});/g, (whole, name2) => {
1547
+ if (name2[0] !== "#") return NAMED_ENTITIES.get(name2) ?? whole;
1548
+ const code = name2[1] === "x" || name2[1] === "X" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
1561
1549
  if (code <= 0 || code > 1114111 || code >= 55296 && code <= 57343) return whole;
1562
1550
  return String.fromCodePoint(code);
1563
1551
  });
@@ -1631,10 +1619,10 @@ function scanXML(text, onChild) {
1631
1619
  } else if (text[i + 1] === "/") {
1632
1620
  const end = text.indexOf(">", i + 2);
1633
1621
  if (end === -1) break;
1634
- const name = trimSpace(text.slice(i + 2, end));
1622
+ const name2 = trimSpace(text.slice(i + 2, end));
1635
1623
  i = end + 1;
1636
1624
  for (let index = stack.length - 1; index >= 0; index -= 1) {
1637
- if (stack[index].name === name) {
1625
+ if (stack[index].name === name2) {
1638
1626
  close(index);
1639
1627
  break;
1640
1628
  }
@@ -1668,7 +1656,7 @@ function scanXML(text, onChild) {
1668
1656
  j += 1;
1669
1657
  continue;
1670
1658
  }
1671
- const name = text.slice(nameStart, j);
1659
+ const name2 = text.slice(nameStart, j);
1672
1660
  while (j < n && isSpace(text[j])) j += 1;
1673
1661
  let value = "";
1674
1662
  if (text[j] === "=") {
@@ -1685,7 +1673,7 @@ function scanXML(text, onChild) {
1685
1673
  value = text.slice(valueStart, j);
1686
1674
  }
1687
1675
  }
1688
- element.attributes[name] = decodeEntities(value);
1676
+ element.attributes[name2] = decodeEntities(value);
1689
1677
  }
1690
1678
  }
1691
1679
  if (!closed) break;
@@ -1699,9 +1687,9 @@ function scanXML(text, onChild) {
1699
1687
  close(0);
1700
1688
  return root;
1701
1689
  }
1702
- var child = (element, name) => element.children.find((item) => item.name === name);
1703
- function childText(element, name) {
1704
- const found = child(element, name);
1690
+ var child = (element, name2) => element.children.find((item) => item.name === name2);
1691
+ function childText(element, name2) {
1692
+ const found = child(element, name2);
1705
1693
  if (found === void 0) return void 0;
1706
1694
  const text = trimSpace(found.text);
1707
1695
  return text === "" ? void 0 : text;
@@ -1821,7 +1809,7 @@ var VLC_HEADERS = /* @__PURE__ */ new Map([["http-user-agent", "User-Agent"], ["
1821
1809
  function parseM3U(data) {
1822
1810
  const playlist = { guideURLs: [], attributes: {}, entries: [] };
1823
1811
  let info;
1824
- let headers = /* @__PURE__ */ new Map();
1812
+ let headers2 = /* @__PURE__ */ new Map();
1825
1813
  let group;
1826
1814
  for (const raw of splitLines(textOf(data))) {
1827
1815
  const line = trimSpace(raw);
@@ -1837,17 +1825,17 @@ function parseM3U(data) {
1837
1825
  tvgName,
1838
1826
  logo: nonEmpty(attributes.get("tvg-logo")),
1839
1827
  group: nonEmpty(attributes.get("group-title")) ?? group,
1840
- headers: headers.size === 0 ? void 0 : Object.fromEntries(headers),
1828
+ headers: headers2.size === 0 ? void 0 : Object.fromEntries(headers2),
1841
1829
  attributes: Object.fromEntries(attributes)
1842
1830
  }));
1843
1831
  info = void 0;
1844
- headers = /* @__PURE__ */ new Map();
1832
+ headers2 = /* @__PURE__ */ new Map();
1845
1833
  group = void 0;
1846
1834
  continue;
1847
1835
  }
1848
- const name = /^[^: \t]*/.exec(line)[0];
1849
- const directive = asciiLower(name);
1850
- const value = line[name.length] === ":" ? line.slice(name.length + 1) : line.slice(name.length);
1836
+ const name2 = /^[^: \t]*/.exec(line)[0];
1837
+ const directive = asciiLower(name2);
1838
+ const value = line[name2.length] === ":" ? line.slice(name2.length + 1) : line.slice(name2.length);
1851
1839
  if (directive === "#extm3u") {
1852
1840
  const { attributes } = readAttributes(value);
1853
1841
  playlist.attributes = { ...playlist.attributes, ...Object.fromEntries(attributes) };
@@ -1864,9 +1852,9 @@ function parseM3U(data) {
1864
1852
  info = { duration: Number.isFinite(seconds) ? seconds : -1, attributes, title: trimSpace(rest ?? "") };
1865
1853
  } else if (directive === "#extvlcopt") {
1866
1854
  const equals = value.indexOf("=");
1867
- const name2 = VLC_HEADERS.get(asciiLower(trimSpace(equals === -1 ? value : value.slice(0, equals))));
1855
+ const name3 = VLC_HEADERS.get(asciiLower(trimSpace(equals === -1 ? value : value.slice(0, equals))));
1868
1856
  const headerValue = equals === -1 ? "" : trimSpace(value.slice(equals + 1));
1869
- if (name2 !== void 0 && headerValue !== "") headers.set(name2, headerValue);
1857
+ if (name3 !== void 0 && headerValue !== "") headers2.set(name3, headerValue);
1870
1858
  } else if (directive === "#extgrp") {
1871
1859
  group = nonEmpty(value);
1872
1860
  }
@@ -1881,8 +1869,8 @@ function parseXML(data) {
1881
1869
  }
1882
1870
  function withNamespaces(element, inherited) {
1883
1871
  let scope = inherited;
1884
- for (const [name, value] of Object.entries(element.attributes)) {
1885
- const prefix2 = name === "xmlns" ? "" : name.startsWith("xmlns:") ? name.slice(6) : void 0;
1872
+ for (const [name2, value] of Object.entries(element.attributes)) {
1873
+ const prefix2 = name2 === "xmlns" ? "" : name2.startsWith("xmlns:") ? name2.slice(6) : void 0;
1886
1874
  if (prefix2 === void 0 || prefix2 === "xml") continue;
1887
1875
  if (scope === inherited) scope = new Map(inherited);
1888
1876
  if (value === "") scope.delete(prefix2);
@@ -1946,7 +1934,7 @@ function parseXMLTV(data) {
1946
1934
  if (id === void 0) return;
1947
1935
  guide.channels.push(compact({
1948
1936
  id,
1949
- names: element.children.filter((item) => item.name === "display-name").map((item) => trimSpace(item.text)).filter((name) => name !== ""),
1937
+ names: element.children.filter((item) => item.name === "display-name").map((item) => trimSpace(item.text)).filter((name2) => name2 !== ""),
1950
1938
  icon: nonEmpty(child(element, "icon")?.attributes.src)
1951
1939
  }));
1952
1940
  } else if (element.name === "programme") {
@@ -1961,7 +1949,7 @@ function parseXMLTV(data) {
1961
1949
  title: childText(element, "title") ?? "",
1962
1950
  subtitle: childText(element, "sub-title"),
1963
1951
  description: childText(element, "desc"),
1964
- categories: element.children.filter((item) => item.name === "category").map((item) => trimSpace(item.text)).filter((name) => name !== ""),
1952
+ categories: element.children.filter((item) => item.name === "category").map((item) => trimSpace(item.text)).filter((name2) => name2 !== ""),
1965
1953
  icon: nonEmpty(child(element, "icon")?.attributes.src)
1966
1954
  }));
1967
1955
  }
@@ -1977,7 +1965,7 @@ function programmesIn(guide, query) {
1977
1965
  });
1978
1966
  }
1979
1967
 
1980
- // plugins/host/metadata.ts
1968
+ // host/metadata.ts
1981
1969
  var MetadataError = class extends Error {
1982
1970
  failure;
1983
1971
  constructor(failure2) {
@@ -2005,18 +1993,19 @@ function checkSearch(query, year) {
2005
1993
  if (year !== void 0) checkYear(year);
2006
1994
  return trimmed;
2007
1995
  }
2008
- function checkList(name, kind, { genre, country, year }) {
2009
- if (name === "upcoming" && kind === "series" || name === "onAir" && kind === "movie") {
2010
- throw invalid(`${name} has no ${kind} list`);
1996
+ function checkList(name2, kind, { genre, country, year, network }) {
1997
+ if ((name2 === "upcoming" || name2 === "nowPlaying") && kind === "series" || name2 === "onAir" && kind === "movie") {
1998
+ throw invalid(`${name2} has no ${kind} list`);
2011
1999
  }
2012
- const filtered = genre !== void 0 || country !== void 0 || year !== void 0;
2013
- if (name !== "popular" && name !== "topRated") {
2014
- if (filtered) throw invalid(`${name} cannot be filtered`);
2000
+ const filtered = genre !== void 0 || country !== void 0 || year !== void 0 || network !== void 0;
2001
+ if (name2 !== "popular" && name2 !== "topRated") {
2002
+ if (filtered) throw invalid(`${name2} cannot be filtered`);
2015
2003
  return;
2016
2004
  }
2017
2005
  if (genre !== void 0 && !GENRES[kind].has(genre)) throw invalid(`genre ${genre} has no ${kind} list`);
2018
2006
  if (country !== void 0 && !/^[A-Z]{2}$/.test(country)) throw invalid("country must be a two-letter ISO 3166-1 code");
2019
2007
  if (year !== void 0) checkYear(year);
2008
+ if (network !== void 0 && kind === "movie") throw invalid("network has no movie list");
2020
2009
  }
2021
2010
  var fail = (message) => new TypeError(message);
2022
2011
  var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);
@@ -2033,16 +2022,16 @@ function optionsOf(value, allowed, fn) {
2033
2022
  if (unknown !== void 0) throw fail(`krillplayer.metadata.${fn}: unknown option ${unknown}`);
2034
2023
  return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== null && entry !== void 0));
2035
2024
  }
2036
- function integerOf(value, name) {
2025
+ function integerOf(value, name2) {
2037
2026
  if (value === void 0) return void 0;
2038
2027
  if (typeof value !== "number" || !Number.isInteger(value) || Math.abs(value) >= 1e9) {
2039
- throw fail(`krillplayer.metadata: ${name} must be an integer`);
2028
+ throw fail(`krillplayer.metadata: ${name2} must be an integer`);
2040
2029
  }
2041
2030
  return value;
2042
2031
  }
2043
- function textOf2(value, name) {
2032
+ function textOf2(value, name2) {
2044
2033
  if (value === void 0) return void 0;
2045
- if (typeof value !== "string") throw fail(`krillplayer.metadata: ${name} must be a string`);
2034
+ if (typeof value !== "string") throw fail(`krillplayer.metadata: ${name2} must be a string`);
2046
2035
  return value;
2047
2036
  }
2048
2037
  var optional2 = (key, value) => value === void 0 ? {} : { [key]: value };
@@ -2092,29 +2081,34 @@ function createMetadata(service) {
2092
2081
  }
2093
2082
  return run2(() => metadata.work(checkedKind, values));
2094
2083
  },
2095
- async list(name, kind, options) {
2084
+ async list(name2, kind, options) {
2096
2085
  const metadata = available();
2097
- if (typeof name !== "string" || !ListName.values.includes(name)) {
2086
+ if (typeof name2 !== "string" || !ListName.values.includes(name2)) {
2098
2087
  throw fail(`krillplayer.metadata.list needs a list name: ${ListName.values.join(", ")}`);
2099
2088
  }
2100
2089
  const checkedKind = kindOf(kind);
2101
- const fields = optionsOf(options, ["genre", "country", "year", "cursor"], "list");
2090
+ const fields = optionsOf(options, ["genre", "country", "year", "network", "cursor"], "list");
2102
2091
  const genre = textOf2(fields.genre, "genre");
2103
2092
  if (genre !== void 0 && !Genre.values.includes(genre)) {
2104
2093
  throw fail(`krillplayer.metadata.list: unknown genre ${genre}`);
2105
2094
  }
2095
+ const network = textOf2(fields.network, "network");
2096
+ if (network !== void 0 && !Network.values.includes(network)) {
2097
+ throw fail(`krillplayer.metadata.list: unknown network ${network}`);
2098
+ }
2106
2099
  const filter = {
2107
2100
  ...genre === void 0 ? {} : { genre },
2108
2101
  ...optional2("country", textOf2(fields.country, "country")),
2109
- ...optional2("year", integerOf(fields.year, "year"))
2102
+ ...optional2("year", integerOf(fields.year, "year")),
2103
+ ...network === void 0 ? {} : { network }
2110
2104
  };
2111
2105
  const cursor = textOf2(fields.cursor, "cursor");
2112
- return run2(() => metadata.list(name, checkedKind, filter, cursor));
2106
+ return run2(() => metadata.list(name2, checkedKind, filter, cursor));
2113
2107
  }
2114
2108
  };
2115
2109
  }
2116
2110
 
2117
- // plugins/host/json-depth.ts
2111
+ // host/json-depth.ts
2118
2112
  function pluginJSONText(bytes2) {
2119
2113
  if (bytes2[0] === 239 && bytes2[1] === 187 && bytes2[2] === 191) return void 0;
2120
2114
  if (bytes2.includes(0)) return void 0;
@@ -2145,7 +2139,7 @@ function nestedTooDeep(json, limit = VALUE_LIMITS.depth) {
2145
2139
  return false;
2146
2140
  }
2147
2141
 
2148
- // plugins/host/crypto.ts
2142
+ // host/crypto.ts
2149
2143
  var RSA = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP"];
2150
2144
  var AES = ["AES-CTR", "AES-CBC", "AES-GCM"];
2151
2145
  var SIGNING = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "ECDSA", "Ed25519", "HMAC"];
@@ -2155,7 +2149,7 @@ var KDF = ["HKDF", "PBKDF2"];
2155
2149
  var AGREEMENT = ["ECDH", "X25519"];
2156
2150
  var WRAPPING = ["AES-KW", ...ENCRYPTION];
2157
2151
  var SUPPORTED = {
2158
- generateKey: CryptoAlgorithm.values.filter((name) => !KDF.includes(name)),
2152
+ generateKey: CryptoAlgorithm.values.filter((name2) => !KDF.includes(name2)),
2159
2153
  importKey: CryptoAlgorithm.values,
2160
2154
  exportKey: CryptoAlgorithm.values,
2161
2155
  sign: SIGNING,
@@ -2184,9 +2178,9 @@ var USAGES = {
2184
2178
  HKDF: { secret: ["deriveKey", "deriveBits"] },
2185
2179
  PBKDF2: { secret: ["deriveKey", "deriveBits"] }
2186
2180
  };
2187
- var ktyOf = (name) => RSA.includes(name) ? "RSA" : name === "ECDSA" || name === "ECDH" ? "EC" : name === "Ed25519" || name === "X25519" ? "OKP" : "oct";
2181
+ var ktyOf = (name2) => RSA.includes(name2) ? "RSA" : name2 === "ECDSA" || name2 === "ECDH" ? "EC" : name2 === "Ed25519" || name2 === "X25519" ? "OKP" : "oct";
2188
2182
  var ELLIPTIC = ["ECDSA", "ECDH"];
2189
- var fixedCurve = (name) => name === "Ed25519" || name === "X25519" ? name : void 0;
2183
+ var fixedCurve = (name2) => name2 === "Ed25519" || name2 === "X25519" ? name2 : void 0;
2190
2184
  var HASH_BYTES = { "SHA-1": 20, "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 };
2191
2185
  var HASH_BLOCK_BITS = { "SHA-1": 512, "SHA-256": 512, "SHA-384": 1024, "SHA-512": 1024 };
2192
2186
  var COORDINATE_BYTES = { "P-256": 32, "P-384": 48, "P-521": 66 };
@@ -2267,20 +2261,20 @@ function algorithmOf(operation, algorithm, listing = operation) {
2267
2261
  const params = typeof algorithm === "string" ? { name: algorithm } : isObject2(algorithm) ? algorithm : void 0;
2268
2262
  if (params === void 0 || typeof params.name !== "string") throw fail2(operation, "algorithm needs a name");
2269
2263
  const given = params.name;
2270
- const name = CryptoAlgorithm.values.find((value) => value.toLowerCase() === given.toLowerCase());
2271
- if (name === void 0 || !SUPPORTED[listing].includes(name)) throw fail2(operation, `${given} is not a supported algorithm for ${operation}`);
2272
- return { name, params };
2264
+ const name2 = CryptoAlgorithm.values.find((value) => value.toLowerCase() === given.toLowerCase());
2265
+ if (name2 === void 0 || !SUPPORTED[listing].includes(name2)) throw fail2(operation, `${given} is not a supported algorithm for ${operation}`);
2266
+ return { name: name2, params };
2273
2267
  }
2274
2268
  function hashOf(operation, value, owner) {
2275
2269
  const given = typeof value === "string" ? value : isObject2(value) && typeof value.name === "string" ? value.name : void 0;
2276
2270
  if (given === void 0) throw fail2(operation, `${owner} needs hash`);
2277
- const hash = CryptoHash.values.find((name) => name.toLowerCase() === given.toLowerCase());
2271
+ const hash = CryptoHash.values.find((name2) => name2.toLowerCase() === given.toLowerCase());
2278
2272
  if (hash === void 0) throw fail2(operation, `${given} is not a supported hash (SHA-1, SHA-256, SHA-384, SHA-512)`);
2279
2273
  return hash;
2280
2274
  }
2281
2275
  function curveOf(operation, value, owner) {
2282
2276
  if (typeof value !== "string") throw fail2(operation, `${owner} needs namedCurve`);
2283
- const curve = CryptoNamedCurve.values.find((name) => name === value);
2277
+ const curve = CryptoNamedCurve.values.find((name2) => name2 === value);
2284
2278
  if (curve === void 0) throw fail2(operation, `${value} is not a supported curve (P-256, P-384, P-521)`);
2285
2279
  return curve;
2286
2280
  }
@@ -2309,7 +2303,7 @@ function usagesOf(operation, value) {
2309
2303
  return CryptoKeyUsage.values.filter((usage) => value.includes(usage));
2310
2304
  }
2311
2305
  function formatOf(operation, value) {
2312
- const format2 = CryptoKeyFormat.values.find((name) => name === value);
2306
+ const format2 = CryptoKeyFormat.values.find((name2) => name2 === value);
2313
2307
  if (format2 === void 0) throw fail2(operation, `${typeof value === "string" ? value : "the format"} is not a key format (raw, spki, pkcs8, jwk)`);
2314
2308
  return format2;
2315
2309
  }
@@ -2319,46 +2313,46 @@ async function keyOf(operation, value, what = "key") {
2319
2313
  const { type, extractable, algorithm, usages, material } = value;
2320
2314
  if (type !== "secret" && type !== "public" && type !== "private") throw bad();
2321
2315
  if (typeof extractable !== "boolean" || !Array.isArray(usages) || usages.some((usage) => !CryptoKeyUsage.values.includes(usage))) throw bad();
2322
- const name = CryptoAlgorithm.values.find((known) => known === algorithm.name);
2323
- if (name === void 0 || typeof material.kty !== "string") throw bad();
2316
+ const name2 = CryptoAlgorithm.values.find((known) => known === algorithm.name);
2317
+ if (name2 === void 0 || typeof material.kty !== "string") throw bad();
2324
2318
  if (!Object.values(material).every((field) => typeof field === "string") || !fieldsFit(material)) throw bad();
2325
2319
  const hash = isObject2(algorithm.hash) ? CryptoHash.values.find((known) => known === algorithm.hash.name) : void 0;
2326
- if ((RSA.includes(name) || name === "HMAC") && hash === void 0) throw bad();
2327
- const expected = USAGES[name][type];
2320
+ if ((RSA.includes(name2) || name2 === "HMAC") && hash === void 0) throw bad();
2321
+ const expected = USAGES[name2][type];
2328
2322
  if (expected === void 0 || usages.some((usage) => !expected.includes(usage))) throw bad();
2329
- if (material.kty !== ktyOf(name) || type === "private" !== (material.d !== void 0)) throw bad();
2330
- if (ELLIPTIC.includes(name) && (!CryptoNamedCurve.values.includes(algorithm.namedCurve) || material.crv !== algorithm.namedCurve)) throw bad();
2331
- if (fixedCurve(name) !== void 0 && material.crv !== fixedCurve(name)) throw bad();
2332
- if (KDF.includes(name) && extractable) throw bad();
2333
- if (!usableMaterial(name, type, material, algorithm.namedCurve)) throw bad();
2334
- const derived = keyAlgorithm(name, material, { hash, curve: algorithm.namedCurve });
2323
+ if (material.kty !== ktyOf(name2) || type === "private" !== (material.d !== void 0)) throw bad();
2324
+ if (ELLIPTIC.includes(name2) && (!CryptoNamedCurve.values.includes(algorithm.namedCurve) || material.crv !== algorithm.namedCurve)) throw bad();
2325
+ if (fixedCurve(name2) !== void 0 && material.crv !== fixedCurve(name2)) throw bad();
2326
+ if (KDF.includes(name2) && extractable) throw bad();
2327
+ if (!usableMaterial(name2, type, material, algorithm.namedCurve)) throw bad();
2328
+ const derived = keyAlgorithm(name2, material, { hash, curve: algorithm.namedCurve });
2335
2329
  if (!sameSize(algorithm.modulusLength, derived.modulusLength) || !sameSize(algorithm.length, derived.length)) throw bad();
2336
2330
  const key = makeKey(type, extractable, derived, usages, material);
2337
2331
  try {
2338
- await webKey(key, USAGES[name][type][0]);
2339
- if (type === "private" && (ELLIPTIC.includes(name) || fixedCurve(name) !== void 0)) await checkPair(key.material, name, key.algorithm.namedCurve);
2332
+ await webKey(key, USAGES[name2][type][0]);
2333
+ if (type === "private" && (ELLIPTIC.includes(name2) || fixedCurve(name2) !== void 0)) await checkPair(key.material, name2, key.algorithm.namedCurve);
2340
2334
  } catch {
2341
2335
  throw bad();
2342
2336
  }
2343
2337
  return key;
2344
2338
  }
2345
- function usableMaterial(name, type, material, curve) {
2339
+ function usableMaterial(name2, type, material, curve) {
2346
2340
  const size = (field) => fromBase64url(material[field])?.length;
2347
- if (name === "HMAC") return (size("k") ?? 0) > 0 && size("k") <= MAX_HMAC_BYTES;
2348
- if (AES_KEYS.includes(name)) return [16, 24, 32].includes(size("k") ?? 0);
2349
- if (KDF.includes(name)) return size("k") !== void 0 && size("k") <= MAX_DERIVE_BYTES;
2350
- if (RSA.includes(name)) {
2341
+ if (name2 === "HMAC") return (size("k") ?? 0) > 0 && size("k") <= MAX_HMAC_BYTES;
2342
+ if (AES_KEYS.includes(name2)) return [16, 24, 32].includes(size("k") ?? 0);
2343
+ if (KDF.includes(name2)) return size("k") !== void 0 && size("k") <= MAX_DERIVE_BYTES;
2344
+ if (RSA.includes(name2)) {
2351
2345
  const modulus = fromBase64url(material.n);
2352
2346
  const parts = type === "private" ? PRIVATE_FIELDS : [];
2353
2347
  return modulus !== void 0 && bitLength(modulus) >= 512 && (size("e") ?? 0) > 0 && parts.every((field) => size(field) !== void 0);
2354
2348
  }
2355
- const coordinate = ELLIPTIC.includes(name) ? COORDINATE_BYTES[curve] : 32;
2356
- const fields = [...ELLIPTIC.includes(name) ? ["x", "y"] : ["x"], ...type === "private" ? ["d"] : []];
2349
+ const coordinate = ELLIPTIC.includes(name2) ? COORDINATE_BYTES[curve] : 32;
2350
+ const fields = [...ELLIPTIC.includes(name2) ? ["x", "y"] : ["x"], ...type === "private" ? ["d"] : []];
2357
2351
  return fields.every((field) => size(field) === coordinate);
2358
2352
  }
2359
2353
  var sameSize = (given, derived) => derived === void 0 ? given === void 0 : given === derived;
2360
- function checkKey(operation, key, name, usage) {
2361
- if (key.algorithm.name !== name) throw fail2(operation, `the key is ${article(key.algorithm.name)} ${key.algorithm.name} key, not ${name}`);
2354
+ function checkKey(operation, key, name2, usage) {
2355
+ if (key.algorithm.name !== name2) throw fail2(operation, `the key is ${article(key.algorithm.name)} ${key.algorithm.name} key, not ${name2}`);
2362
2356
  if (!key.usages.includes(usage)) throw fail2(operation, `the key's usages do not include ${usage}`);
2363
2357
  }
2364
2358
  function requireType(operation, key, type) {
@@ -2383,14 +2377,14 @@ var stripZeros = (bytes2) => {
2383
2377
  const first = bytes2.findIndex((byte) => byte !== 0);
2384
2378
  return first < 0 ? new Uint8Array(0) : bytes2.slice(first);
2385
2379
  };
2386
- function keyAlgorithm(name, material, extra) {
2387
- if (RSA.includes(name)) {
2388
- return { name, modulusLength: bitLength(fromBase64url(material.n)), publicExponent: stripZeros(fromBase64url(material.e)), hash: { name: extra.hash } };
2380
+ function keyAlgorithm(name2, material, extra) {
2381
+ if (RSA.includes(name2)) {
2382
+ return { name: name2, modulusLength: bitLength(fromBase64url(material.n)), publicExponent: stripZeros(fromBase64url(material.e)), hash: { name: extra.hash } };
2389
2383
  }
2390
- if (ELLIPTIC.includes(name)) return { name, namedCurve: extra.curve };
2391
- if (name === "HMAC") return { name, length: fromBase64url(material.k).length * 8, hash: { name: extra.hash } };
2392
- if (AES_KEYS.includes(name)) return { name, length: fromBase64url(material.k).length * 8 };
2393
- return { name };
2384
+ if (ELLIPTIC.includes(name2)) return { name: name2, namedCurve: extra.curve };
2385
+ if (name2 === "HMAC") return { name: name2, length: fromBase64url(material.k).length * 8, hash: { name: extra.hash } };
2386
+ if (AES_KEYS.includes(name2)) return { name: name2, length: fromBase64url(material.k).length * 8 };
2387
+ return { name: name2 };
2394
2388
  }
2395
2389
  var PRIVATE_FIELDS = ["d", "p", "q", "dp", "dq", "qi"];
2396
2390
  var MATERIAL_FIELDS = ["kty", "crv", "x", "y", "n", "e", "d", "p", "q", "dp", "dq", "qi", "k"];
@@ -2401,9 +2395,9 @@ var publicMaterial = (material) => Object.fromEntries(Object.entries(material).f
2401
2395
  function makeKey(type, extractable, algorithm, usages, material) {
2402
2396
  return { type, extractable, algorithm, usages, material };
2403
2397
  }
2404
- function jwkAlg(name, hash, bits, curve) {
2398
+ function jwkAlg(name2, hash, bits, curve) {
2405
2399
  const size = hash?.slice(4);
2406
- switch (name) {
2400
+ switch (name2) {
2407
2401
  case "RSASSA-PKCS1-v1_5":
2408
2402
  return `RS${size}`;
2409
2403
  case "RSA-PSS":
@@ -2416,7 +2410,7 @@ function jwkAlg(name, hash, bits, curve) {
2416
2410
  case "AES-CBC":
2417
2411
  case "AES-GCM":
2418
2412
  case "AES-KW":
2419
- return `A${bits}${name.slice(4)}`;
2413
+ return `A${bits}${name2.slice(4)}`;
2420
2414
  case "Ed25519":
2421
2415
  return "Ed25519";
2422
2416
  case "ECDSA":
@@ -2430,62 +2424,62 @@ function jwkAlg(name, hash, bits, curve) {
2430
2424
  }
2431
2425
  async function generateKey(algorithm, extractableValue, usagesValue) {
2432
2426
  const operation = "generateKey";
2433
- const { name, params } = algorithmOf(operation, algorithm);
2427
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2434
2428
  const extractable = extractableOf(operation, extractableValue);
2435
2429
  const usages = usagesOf(operation, usagesValue);
2436
- const allowed = Object.values(USAGES[name]).flat();
2430
+ const allowed = Object.values(USAGES[name2]).flat();
2437
2431
  let hash;
2438
2432
  let curve;
2439
- if (RSA.includes(name)) {
2440
- const modulusLength = integerOf2(operation, params, "modulusLength", name);
2441
- const exponent = bytesParam(operation, params, "publicExponent", name);
2442
- hash = hashOf(operation, params.hash, name);
2443
- checkGeneratedUsages(operation, name, usages, allowed);
2433
+ if (RSA.includes(name2)) {
2434
+ const modulusLength = integerOf2(operation, params, "modulusLength", name2);
2435
+ const exponent = bytesParam(operation, params, "publicExponent", name2);
2436
+ hash = hashOf(operation, params.hash, name2);
2437
+ checkGeneratedUsages(operation, name2, usages, allowed);
2444
2438
  if (!RSA_MODULUS_LENGTHS.includes(modulusLength)) throw fail2(operation, `modulusLength must be 1024, 2048, 3072 or 4096, not ${modulusLength}`);
2445
2439
  if (stripZeros(exponent).join() !== "1,0,1") throw fail2(operation, "publicExponent must be 65537 ([1, 0, 1])");
2446
- } else if (ELLIPTIC.includes(name)) {
2447
- curve = curveOf(operation, params.namedCurve, name);
2448
- checkGeneratedUsages(operation, name, usages, allowed);
2449
- } else if (name === "HMAC") {
2450
- hash = hashOf(operation, params.hash, name);
2451
- const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name);
2452
- checkGeneratedUsages(operation, name, usages, allowed);
2440
+ } else if (ELLIPTIC.includes(name2)) {
2441
+ curve = curveOf(operation, params.namedCurve, name2);
2442
+ checkGeneratedUsages(operation, name2, usages, allowed);
2443
+ } else if (name2 === "HMAC") {
2444
+ hash = hashOf(operation, params.hash, name2);
2445
+ const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name2);
2446
+ checkGeneratedUsages(operation, name2, usages, allowed);
2453
2447
  if (length <= 0 || length % 8 !== 0) throw fail2(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
2454
2448
  if (length > MAX_HMAC_BYTES * 8) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
2455
- return secretKey(operation, name, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)), hash);
2456
- } else if (AES_KEYS.includes(name)) {
2457
- const length = integerOf2(operation, params, "length", name);
2458
- checkGeneratedUsages(operation, name, usages, allowed);
2449
+ return secretKey(operation, name2, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)), hash);
2450
+ } else if (AES_KEYS.includes(name2)) {
2451
+ const length = integerOf2(operation, params, "length", name2);
2452
+ checkGeneratedUsages(operation, name2, usages, allowed);
2459
2453
  if (![128, 192, 256].includes(length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
2460
- return secretKey(operation, name, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)));
2454
+ return secretKey(operation, name2, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)));
2461
2455
  } else {
2462
- checkGeneratedUsages(operation, name, usages, allowed);
2456
+ checkGeneratedUsages(operation, name2, usages, allowed);
2463
2457
  }
2464
- const privateUsages = usages.filter((usage) => USAGES[name].private.includes(usage));
2465
- const publicUsages = usages.filter((usage) => USAGES[name].public.includes(usage));
2458
+ const privateUsages = usages.filter((usage) => USAGES[name2].private.includes(usage));
2459
+ const publicUsages = usages.filter((usage) => USAGES[name2].public.includes(usage));
2466
2460
  if (privateUsages.length === 0) throw fail2(operation, "a private key needs at least one usage");
2467
2461
  const generated = await subtle().generateKey(
2468
- RSA.includes(name) ? { name, modulusLength: integerOf2(operation, params, "modulusLength", name), publicExponent: new Uint8Array([1, 0, 1]), hash } : ELLIPTIC.includes(name) ? { name, namedCurve: curve } : { name },
2462
+ RSA.includes(name2) ? { name: name2, modulusLength: integerOf2(operation, params, "modulusLength", name2), publicExponent: new Uint8Array([1, 0, 1]), hash } : ELLIPTIC.includes(name2) ? { name: name2, namedCurve: curve } : { name: name2 },
2469
2463
  true,
2470
- [...USAGES[name].private, ...USAGES[name].public]
2464
+ [...USAGES[name2].private, ...USAGES[name2].public]
2471
2465
  );
2472
2466
  const material = materialOf(await subtle().exportKey("jwk", generated.privateKey));
2473
- const keyAlg = keyAlgorithm(name, material, { hash, curve });
2467
+ const keyAlg = keyAlgorithm(name2, material, { hash, curve });
2474
2468
  return {
2475
2469
  publicKey: makeKey("public", true, keyAlg, publicUsages, publicMaterial(material)),
2476
2470
  privateKey: makeKey("private", extractable, keyAlg, privateUsages, material)
2477
2471
  };
2478
2472
  }
2479
- function checkGeneratedUsages(operation, name, usages, allowed) {
2473
+ function checkGeneratedUsages(operation, name2, usages, allowed) {
2480
2474
  const wrong = usages.find((usage) => !allowed.includes(usage));
2481
- if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of ${name} keys`);
2475
+ if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of ${name2} keys`);
2482
2476
  }
2483
- function secretKey(operation, name, extractable, usages, bytes2, hash) {
2477
+ function secretKey(operation, name2, extractable, usages, bytes2, hash) {
2484
2478
  if (usages.length === 0) throw fail2(operation, "a secret key needs at least one usage");
2485
2479
  const material = { kty: "oct", k: base64url(bytes2) };
2486
- return makeKey("secret", extractable, keyAlgorithm(name, material, { hash }), usages, material);
2480
+ return makeKey("secret", extractable, keyAlgorithm(name2, material, { hash }), usages, material);
2487
2481
  }
2488
- var IMPORT_FORMATS = (name) => RSA.includes(name) ? ["spki", "pkcs8", "jwk"] : KDF.includes(name) ? ["raw"] : ELLIPTIC.includes(name) || fixedCurve(name) !== void 0 ? ["raw", "spki", "pkcs8", "jwk"] : ["raw", "jwk"];
2482
+ var IMPORT_FORMATS = (name2) => RSA.includes(name2) ? ["spki", "pkcs8", "jwk"] : KDF.includes(name2) ? ["raw"] : ELLIPTIC.includes(name2) || fixedCurve(name2) !== void 0 ? ["raw", "spki", "pkcs8", "jwk"] : ["raw", "jwk"];
2489
2483
  function importKey(formatValue, keyData, algorithm, extractableValue, usagesValue) {
2490
2484
  return importKeyAs("importKey", formatValue, keyData, algorithm, extractableValue, usagesValue);
2491
2485
  }
@@ -2497,51 +2491,51 @@ async function importKeyAs(operation, formatValue, keyData, algorithm, extractab
2497
2491
  const given = format2 === "jwk" ? void 0 : bytesArgument(operation, keyData, "keyData");
2498
2492
  if (given !== void 0 && given.length > MAX_KEY_BYTES) throw fail2(operation, `keyData can be at most ${MAX_KEY_BYTES} bytes, not ${given.length}`);
2499
2493
  const data = given === void 0 ? void 0 : fromPEM(operation, format2, given);
2500
- const { name, params } = algorithmOf(operation, algorithm, "importKey");
2501
- const hash = RSA.includes(name) || name === "HMAC" ? hashOf(operation, params.hash, name) : void 0;
2502
- const curve = ELLIPTIC.includes(name) ? curveOf(operation, params.namedCurve, name) : void 0;
2503
- const hmacLength = name === "HMAC" && params.length !== void 0 ? integerOf2(operation, params, "length", name) : void 0;
2494
+ const { name: name2, params } = algorithmOf(operation, algorithm, "importKey");
2495
+ const hash = RSA.includes(name2) || name2 === "HMAC" ? hashOf(operation, params.hash, name2) : void 0;
2496
+ const curve = ELLIPTIC.includes(name2) ? curveOf(operation, params.namedCurve, name2) : void 0;
2497
+ const hmacLength = name2 === "HMAC" && params.length !== void 0 ? integerOf2(operation, params, "length", name2) : void 0;
2504
2498
  const extractable = extractableOf(operation, extractableValue);
2505
2499
  const usages = usagesOf(operation, usagesValue);
2506
- if (!IMPORT_FORMATS(name).includes(format2)) throw fail2(operation, `${name} keys cannot be imported as ${format2}`);
2507
- const symmetric = name === "HMAC" || AES_KEYS.includes(name) || KDF.includes(name);
2500
+ if (!IMPORT_FORMATS(name2).includes(format2)) throw fail2(operation, `${name2} keys cannot be imported as ${format2}`);
2501
+ const symmetric = name2 === "HMAC" || AES_KEYS.includes(name2) || KDF.includes(name2);
2508
2502
  const type = symmetric ? "secret" : format2 === "pkcs8" || format2 === "jwk" && jwk.d !== void 0 ? "private" : "public";
2509
- const wrong = usages.find((usage) => !USAGES[name][type].includes(usage));
2510
- if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of a ${type} ${name} key`);
2511
- if (KDF.includes(name) && extractable) throw fail2(operation, `${name} keys cannot be extractable`);
2512
- if (jwk !== void 0) checkJWK(operation, jwk, name, type, hash, curve, extractable, usages);
2513
- const invalid2 = () => fail2(operation, `the ${format2} data is not a valid ${name} key`);
2503
+ const wrong = usages.find((usage) => !USAGES[name2][type].includes(usage));
2504
+ if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of a ${type} ${name2} key`);
2505
+ if (KDF.includes(name2) && extractable) throw fail2(operation, `${name2} keys cannot be extractable`);
2506
+ if (jwk !== void 0) checkJWK(operation, jwk, name2, type, hash, curve, extractable, usages);
2507
+ const invalid2 = () => fail2(operation, `the ${format2} data is not a valid ${name2} key`);
2514
2508
  let material;
2515
2509
  if (symmetric) {
2516
2510
  const bytes2 = data ?? fromBase64url(jwk.k);
2517
2511
  if (bytes2 === void 0) throw invalid2();
2518
- if (AES_KEYS.includes(name) && ![16, 24, 32].includes(bytes2.length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${bytes2.length * 8}`);
2519
- if (name === "HMAC" && bytes2.length === 0) throw invalid2();
2520
- if (name === "HMAC" && bytes2.length > MAX_HMAC_BYTES) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${bytes2.length * 8}`);
2521
- if (KDF.includes(name) && bytes2.length > MAX_DERIVE_BYTES) {
2522
- throw fail2(operation, `${name} key material can be at most ${MAX_DERIVE_BYTES * 8} bits, not ${bytes2.length * 8}`);
2512
+ if (AES_KEYS.includes(name2) && ![16, 24, 32].includes(bytes2.length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${bytes2.length * 8}`);
2513
+ if (name2 === "HMAC" && bytes2.length === 0) throw invalid2();
2514
+ if (name2 === "HMAC" && bytes2.length > MAX_HMAC_BYTES) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${bytes2.length * 8}`);
2515
+ if (KDF.includes(name2) && bytes2.length > MAX_DERIVE_BYTES) {
2516
+ throw fail2(operation, `${name2} key material can be at most ${MAX_DERIVE_BYTES * 8} bits, not ${bytes2.length * 8}`);
2523
2517
  }
2524
2518
  if (hmacLength !== void 0 && hmacLength !== bytes2.length * 8) {
2525
2519
  throw fail2(operation, `HMAC length ${hmacLength} does not match the ${bytes2.length * 8}-bit key data`);
2526
2520
  }
2527
2521
  material = { kty: "oct", k: base64url(bytes2) };
2528
2522
  } else {
2529
- if (format2 === "raw" && ELLIPTIC.includes(name) && (data[0] !== 4 || data.length !== 1 + 2 * COORDINATE_BYTES[curve])) throw invalid2();
2530
- if (format2 === "raw" && fixedCurve(name) !== void 0 && data.length !== 32) throw invalid2();
2531
- const imported = await webImport(format2, data ?? materialOf(jwk), name, hash, curve, type).catch(() => {
2523
+ if (format2 === "raw" && ELLIPTIC.includes(name2) && (data[0] !== 4 || data.length !== 1 + 2 * COORDINATE_BYTES[curve])) throw invalid2();
2524
+ if (format2 === "raw" && fixedCurve(name2) !== void 0 && data.length !== 32) throw invalid2();
2525
+ const imported = await webImport(format2, data ?? materialOf(jwk), name2, hash, curve, type).catch(() => {
2532
2526
  throw invalid2();
2533
2527
  });
2534
2528
  material = materialOf(await subtle().exportKey("jwk", imported));
2535
- if (format2 === "jwk" && type === "private" && !RSA.includes(name)) await checkPair(material, name, curve).catch(() => {
2529
+ if (format2 === "jwk" && type === "private" && !RSA.includes(name2)) await checkPair(material, name2, curve).catch(() => {
2536
2530
  throw invalid2();
2537
2531
  });
2538
2532
  }
2539
2533
  if (usages.length === 0 && type !== "public") throw fail2(operation, `a ${type} key needs at least one usage`);
2540
- return makeKey(type, extractable, keyAlgorithm(name, material, { hash, curve }), usages, material);
2534
+ return makeKey(type, extractable, keyAlgorithm(name2, material, { hash, curve }), usages, material);
2541
2535
  }
2542
- function webImport(format2, keyData, name, hash, curve, type) {
2543
- const algorithm = RSA.includes(name) ? { name, hash } : ELLIPTIC.includes(name) ? { name, namedCurve: curve } : { name };
2544
- const usages = [...USAGES[name][type]];
2536
+ function webImport(format2, keyData, name2, hash, curve, type) {
2537
+ const algorithm = RSA.includes(name2) ? { name: name2, hash } : ELLIPTIC.includes(name2) ? { name: name2, namedCurve: curve } : { name: name2 };
2538
+ const usages = [...USAGES[name2][type]];
2545
2539
  return format2 === "jwk" ? subtle().importKey("jwk", { ...keyData, ext: true }, algorithm, true, usages) : subtle().importKey(format2, keyData, algorithm, true, usages);
2546
2540
  }
2547
2541
  async function checkPair(material, keyName, curve) {
@@ -2551,37 +2545,37 @@ async function checkPair(material, keyName, curve) {
2551
2545
  if ((await subtle().exportKey("jwk", imported)).x !== material.x) throw new Error("not a pair");
2552
2546
  return;
2553
2547
  }
2554
- const name = keyName === "ECDH" ? "ECDSA" : keyName;
2555
- const algorithm = name === "ECDSA" ? { name, namedCurve: curve } : { name };
2548
+ const name2 = keyName === "ECDH" ? "ECDSA" : keyName;
2549
+ const algorithm = name2 === "ECDSA" ? { name: name2, namedCurve: curve } : { name: name2 };
2556
2550
  const signer = await subtle().importKey("jwk", { ...material, ext: true }, algorithm, false, ["sign"]);
2557
2551
  const verifier = await subtle().importKey("jwk", { ...publicMaterial(material), ext: true }, algorithm, false, ["verify"]);
2558
- const params = name === "ECDSA" ? { name, hash: "SHA-256" } : { name };
2552
+ const params = name2 === "ECDSA" ? { name: name2, hash: "SHA-256" } : { name: name2 };
2559
2553
  const probe = new Uint8Array([1]);
2560
2554
  const signature = new Uint8Array(await subtle().sign(params, signer, probe));
2561
2555
  if (!await subtle().verify(params, verifier, signature, probe)) throw new Error("not a pair");
2562
2556
  }
2563
2557
  var X25519_PKCS8_PREFIX = [48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 110, 4, 34, 4, 32];
2564
- function checkJWK(operation, jwk, name, type, hash, curve, extractable, usages) {
2565
- const kty = ktyOf(name);
2558
+ function checkJWK(operation, jwk, name2, type, hash, curve, extractable, usages) {
2559
+ const kty = ktyOf(name2);
2566
2560
  if (jwk.kty !== kty) throw fail2(operation, `the JWK kty must be ${kty}`);
2567
- const crv = ELLIPTIC.includes(name) ? curve : fixedCurve(name);
2561
+ const crv = ELLIPTIC.includes(name2) ? curve : fixedCurve(name2);
2568
2562
  if (crv !== void 0 && jwk.crv !== crv) throw fail2(operation, `the JWK crv must be ${crv}`);
2569
- if (jwk.alg !== void 0 && !AGREEMENT.includes(name)) {
2570
- const bits = AES_KEYS.includes(name) ? (fromBase64url(jwk.k)?.length ?? 0) * 8 : void 0;
2571
- const expected = jwkAlg(name, hash, bits, curve);
2572
- if (jwk.alg !== expected && !(name === "Ed25519" && jwk.alg === "EdDSA")) throw fail2(operation, `the JWK alg ${String(jwk.alg)} does not match ${expected}`);
2563
+ if (jwk.alg !== void 0 && !AGREEMENT.includes(name2)) {
2564
+ const bits = AES_KEYS.includes(name2) ? (fromBase64url(jwk.k)?.length ?? 0) * 8 : void 0;
2565
+ const expected = jwkAlg(name2, hash, bits, curve);
2566
+ if (jwk.alg !== expected && !(name2 === "Ed25519" && jwk.alg === "EdDSA")) throw fail2(operation, `the JWK alg ${String(jwk.alg)} does not match ${expected}`);
2573
2567
  }
2574
2568
  if (jwk.use !== void 0 && usages.length > 0) {
2575
- const use = ENCRYPTION.includes(name) || name === "AES-KW" || AGREEMENT.includes(name) ? "enc" : "sig";
2569
+ const use = ENCRYPTION.includes(name2) || name2 === "AES-KW" || AGREEMENT.includes(name2) ? "enc" : "sig";
2576
2570
  if (jwk.use !== use) throw fail2(operation, `the JWK use must be ${use}`);
2577
2571
  }
2578
2572
  if (jwk.key_ops !== void 0) {
2579
- if (!Array.isArray(jwk.key_ops)) throw fail2(operation, `the jwk data is not a valid ${name} key`);
2573
+ if (!Array.isArray(jwk.key_ops)) throw fail2(operation, `the jwk data is not a valid ${name2} key`);
2580
2574
  const missing = usages.find((usage) => !jwk.key_ops.includes(usage));
2581
2575
  if (missing !== void 0) throw fail2(operation, `the JWK key_ops do not include ${missing}`);
2582
2576
  }
2583
2577
  if (jwk.ext === false && extractable) throw fail2(operation, "the JWK is marked not extractable");
2584
- if (type === "private" && RSA.includes(name) && PRIVATE_FIELDS.some((field) => jwk[field] === void 0)) {
2578
+ if (type === "private" && RSA.includes(name2) && PRIVATE_FIELDS.some((field) => jwk[field] === void 0)) {
2585
2579
  throw fail2(operation, "the JWK has d but not all of p, q, dp, dq, qi");
2586
2580
  }
2587
2581
  }
@@ -2592,76 +2586,76 @@ async function exportKey(formatValue, keyValue) {
2592
2586
  }
2593
2587
  async function exported(operation, format2, key) {
2594
2588
  if (!key.extractable) throw fail2(operation, "the key is not extractable");
2595
- const name = key.algorithm.name;
2596
- const formats = key.type === "secret" ? ["raw", "jwk"] : key.type === "private" ? ["pkcs8", "jwk"] : RSA.includes(name) ? ["spki", "jwk"] : ["raw", "spki", "jwk"];
2597
- if (!formats.includes(format2)) throw fail2(operation, `a ${key.type} ${name} key cannot be exported as ${format2}`);
2589
+ const name2 = key.algorithm.name;
2590
+ const formats = key.type === "secret" ? ["raw", "jwk"] : key.type === "private" ? ["pkcs8", "jwk"] : RSA.includes(name2) ? ["spki", "jwk"] : ["raw", "spki", "jwk"];
2591
+ if (!formats.includes(format2)) throw fail2(operation, `a ${key.type} ${name2} key cannot be exported as ${format2}`);
2598
2592
  if (format2 === "jwk") {
2599
2593
  const bits = key.algorithm.length;
2600
- const alg = jwkAlg(name, key.algorithm.hash?.name, bits, void 0);
2594
+ const alg = jwkAlg(name2, key.algorithm.hash?.name, bits, void 0);
2601
2595
  return { ...key.material, ...alg === void 0 ? {} : { alg }, ext: key.extractable, key_ops: [...key.usages] };
2602
2596
  }
2603
2597
  if (key.type === "secret") return fromBase64url(key.material.k);
2604
- const web = await webImport("jwk", key.material, name, key.algorithm.hash?.name, key.algorithm.namedCurve, key.type);
2598
+ const web = await webImport("jwk", key.material, name2, key.algorithm.hash?.name, key.algorithm.namedCurve, key.type);
2605
2599
  return new Uint8Array(await subtle().exportKey(format2, web));
2606
2600
  }
2607
- function signingParams(operation, name, params) {
2608
- if (name === "RSA-PSS") return { saltLength: integerOf2(operation, params, "saltLength", name) };
2609
- if (name === "ECDSA") return { hash: hashOf(operation, params.hash, name) };
2601
+ function signingParams(operation, name2, params) {
2602
+ if (name2 === "RSA-PSS") return { saltLength: integerOf2(operation, params, "saltLength", name2) };
2603
+ if (name2 === "ECDSA") return { hash: hashOf(operation, params.hash, name2) };
2610
2604
  return {};
2611
2605
  }
2612
- function signingKey(operation, key, name, saltLength) {
2613
- checkKey(operation, key, name, operation);
2614
- requireType(operation, key, name === "HMAC" ? "secret" : operation === "sign" ? "private" : "public");
2615
- if (name === "RSA-PSS" && saltLength !== HASH_BYTES[hashOfKey(key)]) {
2606
+ function signingKey(operation, key, name2, saltLength) {
2607
+ checkKey(operation, key, name2, operation);
2608
+ requireType(operation, key, name2 === "HMAC" ? "secret" : operation === "sign" ? "private" : "public");
2609
+ if (name2 === "RSA-PSS" && saltLength !== HASH_BYTES[hashOfKey(key)]) {
2616
2610
  throw fail2(operation, `RSA-PSS saltLength must be ${HASH_BYTES[hashOfKey(key)]} for ${hashOfKey(key)}, not ${saltLength}`);
2617
2611
  }
2618
2612
  }
2619
- function webSigning(name, extra) {
2620
- return name === "RSA-PSS" ? { name, saltLength: extra.saltLength } : name === "ECDSA" ? { name, hash: extra.hash } : { name };
2613
+ function webSigning(name2, extra) {
2614
+ return name2 === "RSA-PSS" ? { name: name2, saltLength: extra.saltLength } : name2 === "ECDSA" ? { name: name2, hash: extra.hash } : { name: name2 };
2621
2615
  }
2622
2616
  async function sign(algorithm, keyValue, dataValue) {
2623
2617
  const operation = "sign";
2624
- const { name, params } = algorithmOf(operation, algorithm);
2625
- const extra = signingParams(operation, name, params);
2618
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2619
+ const extra = signingParams(operation, name2, params);
2626
2620
  const key = await keyOf(operation, keyValue);
2627
2621
  const data = bytesArgument(operation, dataValue, "data");
2628
- signingKey(operation, key, name, extra.saltLength);
2629
- return new Uint8Array(await subtle().sign(webSigning(name, extra), await webKey(key, "sign"), data));
2622
+ signingKey(operation, key, name2, extra.saltLength);
2623
+ return new Uint8Array(await subtle().sign(webSigning(name2, extra), await webKey(key, "sign"), data));
2630
2624
  }
2631
2625
  async function verify(algorithm, keyValue, signatureValue, dataValue) {
2632
2626
  const operation = "verify";
2633
- const { name, params } = algorithmOf(operation, algorithm);
2634
- const extra = signingParams(operation, name, params);
2627
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2628
+ const extra = signingParams(operation, name2, params);
2635
2629
  const key = await keyOf(operation, keyValue);
2636
2630
  const signature = bytesArgument(operation, signatureValue, "signature");
2637
2631
  const data = bytesArgument(operation, dataValue, "data");
2638
- signingKey(operation, key, name, extra.saltLength);
2639
- return subtle().verify(webSigning(name, extra), await webKey(key, "verify"), signature, data);
2632
+ signingKey(operation, key, name2, extra.saltLength);
2633
+ return subtle().verify(webSigning(name2, extra), await webKey(key, "verify"), signature, data);
2640
2634
  }
2641
- function cipherParams(operation, name, params) {
2642
- switch (name) {
2635
+ function cipherParams(operation, name2, params) {
2636
+ switch (name2) {
2643
2637
  case "RSA-OAEP":
2644
- return { label: optionalBytesParam(operation, params, "label", name) };
2638
+ return { label: optionalBytesParam(operation, params, "label", name2) };
2645
2639
  case "AES-CBC":
2646
- return { iv: bytesParam(operation, params, "iv", name) };
2640
+ return { iv: bytesParam(operation, params, "iv", name2) };
2647
2641
  case "AES-CTR":
2648
- return { counter: bytesParam(operation, params, "counter", name), length: integerOf2(operation, params, "length", name) };
2642
+ return { counter: bytesParam(operation, params, "counter", name2), length: integerOf2(operation, params, "length", name2) };
2649
2643
  default:
2650
2644
  return {
2651
- iv: bytesParam(operation, params, "iv", name),
2652
- additionalData: optionalBytesParam(operation, params, "additionalData", name),
2653
- tagLength: params.tagLength === void 0 ? 128 : integerOf2(operation, params, "tagLength", name)
2645
+ iv: bytesParam(operation, params, "iv", name2),
2646
+ additionalData: optionalBytesParam(operation, params, "additionalData", name2),
2647
+ tagLength: params.tagLength === void 0 ? 128 : integerOf2(operation, params, "tagLength", name2)
2654
2648
  };
2655
2649
  }
2656
2650
  }
2657
- function checkCipher(operation, name, cipher, data, key) {
2658
- if (name === "RSA-OAEP") {
2651
+ function checkCipher(operation, name2, cipher, data, key) {
2652
+ if (name2 === "RSA-OAEP") {
2659
2653
  if (cipher.label !== void 0 && cipher.label.length > 0) throw fail2(operation, "RSA-OAEP does not support a label");
2660
2654
  const max = Math.ceil(bitLength(fromBase64url(key.material.n)) / 8) - 2 * HASH_BYTES[hashOfKey(key)] - 2;
2661
2655
  if ((operation === "encrypt" || operation === "wrapKey") && data.length > max) throw fail2(operation, `the data is longer than ${max} bytes, the most this RSA-OAEP key can encrypt`);
2662
- } else if (name === "AES-CBC") {
2656
+ } else if (name2 === "AES-CBC") {
2663
2657
  if (cipher.iv.length !== 16) throw fail2(operation, `AES-CBC iv must be 16 bytes, not ${cipher.iv.length}`);
2664
- } else if (name === "AES-CTR") {
2658
+ } else if (name2 === "AES-CTR") {
2665
2659
  if (cipher.counter.length !== 16) throw fail2(operation, `AES-CTR counter must be 16 bytes, not ${cipher.counter.length}`);
2666
2660
  if (cipher.length < 1 || cipher.length > 128) throw fail2(operation, `AES-CTR length must be from 1 to 128, not ${cipher.length}`);
2667
2661
  const blocks = Math.ceil(data.length / 16);
@@ -2673,35 +2667,35 @@ function checkCipher(operation, name, cipher, data, key) {
2673
2667
  if (!GCM_TAG_LENGTHS.includes(cipher.tagLength)) throw fail2(operation, `AES-GCM tagLength must be 32, 64, 96, 104, 112, 120 or 128, not ${cipher.tagLength}`);
2674
2668
  }
2675
2669
  }
2676
- function webCipher(name, cipher) {
2677
- switch (name) {
2670
+ function webCipher(name2, cipher) {
2671
+ switch (name2) {
2678
2672
  case "RSA-OAEP":
2679
- return { name };
2673
+ return { name: name2 };
2680
2674
  case "AES-CBC":
2681
- return { name, iv: cipher.iv };
2675
+ return { name: name2, iv: cipher.iv };
2682
2676
  case "AES-CTR":
2683
- return { name, counter: cipher.counter, length: cipher.length };
2677
+ return { name: name2, counter: cipher.counter, length: cipher.length };
2684
2678
  default:
2685
- return { name, iv: cipher.iv, tagLength: cipher.tagLength, ...cipher.additionalData === void 0 ? {} : { additionalData: cipher.additionalData } };
2679
+ return { name: name2, iv: cipher.iv, tagLength: cipher.tagLength, ...cipher.additionalData === void 0 ? {} : { additionalData: cipher.additionalData } };
2686
2680
  }
2687
2681
  }
2688
2682
  async function crypt(operation, algorithm, keyValue, dataValue) {
2689
- const { name, params } = algorithmOf(operation, algorithm);
2690
- const cipher = cipherParams(operation, name, params);
2683
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2684
+ const cipher = cipherParams(operation, name2, params);
2691
2685
  const key = await keyOf(operation, keyValue);
2692
2686
  const data = bytesArgument(operation, dataValue, "data");
2693
- checkKey(operation, key, name, operation);
2694
- requireType(operation, key, name === "RSA-OAEP" ? operation === "encrypt" ? "public" : "private" : "secret");
2695
- checkCipher(operation, name, cipher, data, key);
2687
+ checkKey(operation, key, name2, operation);
2688
+ requireType(operation, key, name2 === "RSA-OAEP" ? operation === "encrypt" ? "public" : "private" : "secret");
2689
+ checkCipher(operation, name2, cipher, data, key);
2696
2690
  const web = await webKey(key, operation);
2697
2691
  try {
2698
- return new Uint8Array(await (operation === "encrypt" ? subtle().encrypt(webCipher(name, cipher), web, data) : subtle().decrypt(webCipher(name, cipher), web, data)));
2692
+ return new Uint8Array(await (operation === "encrypt" ? subtle().encrypt(webCipher(name2, cipher), web, data) : subtle().decrypt(webCipher(name2, cipher), web, data)));
2699
2693
  } catch (error) {
2700
2694
  if (operation === "encrypt") throw error;
2701
- throw decryptionFailed(operation, name);
2695
+ throw decryptionFailed(operation, name2);
2702
2696
  }
2703
2697
  }
2704
- var decryptionFailed = (operation, name) => fail2(operation, name === "AES-GCM" ? "AES-GCM tag check failed" : name === "AES-CBC" ? "AES-CBC decryption failed: the data or its padding is wrong" : name === "AES-KW" ? "AES-KW integrity check failed" : `${name} decryption failed`);
2698
+ var decryptionFailed = (operation, name2) => fail2(operation, name2 === "AES-GCM" ? "AES-GCM tag check failed" : name2 === "AES-CBC" ? "AES-CBC decryption failed: the data or its padding is wrong" : name2 === "AES-KW" ? "AES-KW integrity check failed" : `${name2} decryption failed`);
2705
2699
  async function digest(algorithm, dataValue) {
2706
2700
  const operation = "digest";
2707
2701
  const given = typeof algorithm === "string" ? algorithm : isObject2(algorithm) && typeof algorithm.name === "string" ? algorithm.name : void 0;
@@ -2710,15 +2704,15 @@ async function digest(algorithm, dataValue) {
2710
2704
  return new Uint8Array(await subtle().digest(hash, bytesArgument(operation, dataValue, "data")));
2711
2705
  }
2712
2706
  async function derivationOf(operation, algorithm) {
2713
- const { name, params } = algorithmOf(operation, algorithm);
2714
- if (AGREEMENT.includes(name)) {
2715
- if (params.public === void 0) throw fail2(operation, `${name} needs public`);
2716
- return { name, publicKey: await keyOf(operation, params.public, "public") };
2707
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2708
+ if (AGREEMENT.includes(name2)) {
2709
+ if (params.public === void 0) throw fail2(operation, `${name2} needs public`);
2710
+ return { name: name2, publicKey: await keyOf(operation, params.public, "public") };
2717
2711
  }
2718
- const hash = hashOf(operation, params.hash, name);
2719
- const salt = boundedBytes(operation, params, "salt", name);
2720
- if (name === "HKDF") return { name, hash, salt, info: boundedBytes(operation, params, "info", name) };
2721
- return { name, hash, salt, iterations: integerOf2(operation, params, "iterations", name) };
2712
+ const hash = hashOf(operation, params.hash, name2);
2713
+ const salt = boundedBytes(operation, params, "salt", name2);
2714
+ if (name2 === "HKDF") return { name: name2, hash, salt, info: boundedBytes(operation, params, "info", name2) };
2715
+ return { name: name2, hash, salt, iterations: integerOf2(operation, params, "iterations", name2) };
2722
2716
  }
2723
2717
  function boundedBytes(operation, params, field, owner) {
2724
2718
  const bytes2 = bytesParam(operation, params, field, owner);
@@ -2730,16 +2724,16 @@ function lengthOf(operation, value) {
2730
2724
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value >= 1e15) throw fail2(operation, "length must be a whole number of bits or null");
2731
2725
  return value;
2732
2726
  }
2733
- var article = (name) => /^[AEIOX]/.test(name) ? "an" : "a";
2727
+ var article = (name2) => /^[AEIOX]/.test(name2) ? "an" : "a";
2734
2728
  async function derive(operation, derivation, key, length, usage) {
2735
- const { name } = derivation;
2736
- checkKey(operation, key, name, usage);
2737
- if (AGREEMENT.includes(name)) return agree(operation, derivation, key, length);
2738
- if (length === null) throw fail2(operation, `${name} needs length`);
2739
- if (length % 8 !== 0) throw fail2(operation, `${name} length must be a multiple of 8, not ${length}`);
2740
- if (length > MAX_DERIVE_BYTES * 8) throw fail2(operation, `${name} can derive at most ${MAX_DERIVE_BYTES * 8} bits, not ${length}`);
2729
+ const { name: name2 } = derivation;
2730
+ checkKey(operation, key, name2, usage);
2731
+ if (AGREEMENT.includes(name2)) return agree(operation, derivation, key, length);
2732
+ if (length === null) throw fail2(operation, `${name2} needs length`);
2733
+ if (length % 8 !== 0) throw fail2(operation, `${name2} length must be a multiple of 8, not ${length}`);
2734
+ if (length > MAX_DERIVE_BYTES * 8) throw fail2(operation, `${name2} can derive at most ${MAX_DERIVE_BYTES * 8} bits, not ${length}`);
2741
2735
  const iterations = derivation.iterations ?? 0;
2742
- if (name === "PBKDF2") {
2736
+ if (name2 === "PBKDF2") {
2743
2737
  if (iterations < 1) throw fail2(operation, `PBKDF2 iterations must be at least 1, not ${iterations}`);
2744
2738
  const work = iterations * Math.ceil(length / (HASH_BYTES[derivation.hash] * 8));
2745
2739
  if (work > MAX_PBKDF2_WORK) {
@@ -2747,29 +2741,29 @@ async function derive(operation, derivation, key, length, usage) {
2747
2741
  }
2748
2742
  }
2749
2743
  if (length === 0) return new Uint8Array(0);
2750
- const params = name === "HKDF" ? { name, hash: derivation.hash, salt: derivation.salt, info: derivation.info } : { name, hash: derivation.hash, salt: derivation.salt, iterations };
2744
+ const params = name2 === "HKDF" ? { name: name2, hash: derivation.hash, salt: derivation.salt, info: derivation.info } : { name: name2, hash: derivation.hash, salt: derivation.salt, iterations };
2751
2745
  return new Uint8Array(await subtle().deriveBits(params, await webKey(key, "deriveBits"), length));
2752
2746
  }
2753
2747
  async function agree(operation, derivation, key, length) {
2754
- const { name } = derivation;
2748
+ const { name: name2 } = derivation;
2755
2749
  const other = derivation.publicKey;
2756
2750
  requireType(operation, key, "private");
2757
2751
  if (other.type !== "public") throw fail2(operation, "public must be a public key");
2758
- if (other.algorithm.name !== name) throw fail2(operation, `the public key is ${article(other.algorithm.name)} ${other.algorithm.name} key, not ${name}`);
2752
+ if (other.algorithm.name !== name2) throw fail2(operation, `the public key is ${article(other.algorithm.name)} ${other.algorithm.name} key, not ${name2}`);
2759
2753
  const curve = key.algorithm.namedCurve;
2760
2754
  if (curve !== void 0 && other.algorithm.namedCurve !== curve) throw fail2(operation, `the public key is on ${other.algorithm.namedCurve}, not ${curve}`);
2761
2755
  const full = curve === void 0 ? 256 : COORDINATE_BYTES[curve] * 8;
2762
2756
  if (length !== null && length > full) {
2763
- throw fail2(operation, curve === void 0 ? `${name} can derive at most ${full} bits, not ${length}` : `${name} can derive at most ${full} bits on ${curve}, not ${length}`);
2757
+ throw fail2(operation, curve === void 0 ? `${name2} can derive at most ${full} bits, not ${length}` : `${name2} can derive at most ${full} bits on ${curve}, not ${length}`);
2764
2758
  }
2765
2759
  const smallOrder = () => fail2(operation, "the X25519 shared secret is all zero: the public key is a small-order point");
2766
2760
  let secret;
2767
2761
  try {
2768
- secret = new Uint8Array(await subtle().deriveBits({ name, public: await webKey(other, void 0) }, await webKey(key, "deriveBits"), null));
2762
+ secret = new Uint8Array(await subtle().deriveBits({ name: name2, public: await webKey(other, void 0) }, await webKey(key, "deriveBits"), null));
2769
2763
  } catch {
2770
- throw name === "X25519" ? smallOrder() : fail2(operation, `${name} could not derive bits with this key`);
2764
+ throw name2 === "X25519" ? smallOrder() : fail2(operation, `${name2} could not derive bits with this key`);
2771
2765
  }
2772
- if (name === "X25519" && secret.every((byte) => byte === 0)) throw smallOrder();
2766
+ if (name2 === "X25519" && secret.every((byte) => byte === 0)) throw smallOrder();
2773
2767
  if (length === null) return secret;
2774
2768
  const bits = secret.slice(0, Math.ceil(length / 8));
2775
2769
  if (length % 8 !== 0) bits[bits.length - 1] &= 255 << 8 - length % 8 & 255;
@@ -2781,28 +2775,28 @@ async function deriveBits(algorithm, baseKey, lengthValue) {
2781
2775
  const key = await keyOf(operation, baseKey);
2782
2776
  return derive(operation, derivation, key, lengthOf(operation, lengthValue), "deriveBits");
2783
2777
  }
2784
- function derivedLength(operation, name, params) {
2785
- if (AES_KEYS.includes(name)) {
2786
- const length = integerOf2(operation, params, "length", name);
2778
+ function derivedLength(operation, name2, params) {
2779
+ if (AES_KEYS.includes(name2)) {
2780
+ const length = integerOf2(operation, params, "length", name2);
2787
2781
  if (![128, 192, 256].includes(length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
2788
2782
  return length;
2789
2783
  }
2790
- if (name === "HMAC") {
2791
- const hash = hashOf(operation, params.hash, name);
2792
- const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name);
2784
+ if (name2 === "HMAC") {
2785
+ const hash = hashOf(operation, params.hash, name2);
2786
+ const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name2);
2793
2787
  if (length <= 0 || length % 8 !== 0) throw fail2(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
2794
2788
  if (length > MAX_HMAC_BYTES * 8) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
2795
2789
  return length;
2796
2790
  }
2797
- if (KDF.includes(name)) return null;
2798
- throw fail2(operation, `${name} keys cannot be derived`);
2791
+ if (KDF.includes(name2)) return null;
2792
+ throw fail2(operation, `${name2} keys cannot be derived`);
2799
2793
  }
2800
2794
  async function deriveKey(algorithm, baseKey, derivedKeyType, extractableValue, usagesValue) {
2801
2795
  const operation = "deriveKey";
2802
2796
  const derivation = await derivationOf(operation, algorithm);
2803
2797
  const key = await keyOf(operation, baseKey);
2804
- const { name, params } = algorithmOf(operation, derivedKeyType, "importKey");
2805
- const length = derivedLength(operation, name, params);
2798
+ const { name: name2, params } = algorithmOf(operation, derivedKeyType, "importKey");
2799
+ const length = derivedLength(operation, name2, params);
2806
2800
  extractableOf(operation, extractableValue);
2807
2801
  usagesOf(operation, usagesValue);
2808
2802
  const bits = await derive(operation, derivation, key, length, "deriveKey");
@@ -2814,8 +2808,8 @@ function jwkBytes(jwk, pad) {
2814
2808
  return new TextEncoder().encode(text);
2815
2809
  }
2816
2810
  function wrapping(operation, algorithm) {
2817
- const { name, params } = algorithmOf(operation, algorithm);
2818
- return { name, cipher: name === "AES-KW" ? {} : cipherParams(operation, name, params) };
2811
+ const { name: name2, params } = algorithmOf(operation, algorithm);
2812
+ return { name: name2, cipher: name2 === "AES-KW" ? {} : cipherParams(operation, name2, params) };
2819
2813
  }
2820
2814
  function checkKeyWrap(operation, data) {
2821
2815
  const least = operation === "wrapKey" ? 16 : 24;
@@ -2827,24 +2821,24 @@ var HMAC_CARRIER = { name: "HMAC", hash: "SHA-256" };
2827
2821
  async function wrapKey(formatValue, keyValue, wrappingKeyValue, algorithm) {
2828
2822
  const operation = "wrapKey";
2829
2823
  const format2 = formatOf(operation, formatValue);
2830
- const { name, cipher } = wrapping(operation, algorithm);
2824
+ const { name: name2, cipher } = wrapping(operation, algorithm);
2831
2825
  const key = await keyOf(operation, keyValue);
2832
2826
  const wrappingKey = await keyOf(operation, wrappingKeyValue);
2833
- checkKey(operation, wrappingKey, name, "wrapKey");
2834
- requireType(operation, wrappingKey, name === "RSA-OAEP" ? "public" : "secret");
2827
+ checkKey(operation, wrappingKey, name2, "wrapKey");
2828
+ requireType(operation, wrappingKey, name2 === "RSA-OAEP" ? "public" : "secret");
2835
2829
  const output = await exported(operation, format2, key);
2836
- const data = output instanceof Uint8Array ? output : jwkBytes(output, name === "AES-KW");
2837
- if (name === "AES-KW") {
2830
+ const data = output instanceof Uint8Array ? output : jwkBytes(output, name2 === "AES-KW");
2831
+ if (name2 === "AES-KW") {
2838
2832
  checkKeyWrap(operation, data);
2839
2833
  } else {
2840
- checkCipher(operation, name, cipher, data, wrappingKey);
2834
+ checkCipher(operation, name2, cipher, data, wrappingKey);
2841
2835
  }
2842
2836
  try {
2843
- if (name !== "AES-KW") return new Uint8Array(await subtle().encrypt(webCipher(name, cipher), await webKey(wrappingKey, "encrypt"), data));
2837
+ if (name2 !== "AES-KW") return new Uint8Array(await subtle().encrypt(webCipher(name2, cipher), await webKey(wrappingKey, "encrypt"), data));
2844
2838
  const carrier = await subtle().importKey("raw", data, HMAC_CARRIER, true, ["sign"]);
2845
- return new Uint8Array(await subtle().wrapKey("raw", carrier, await webKey(wrappingKey, "wrapKey"), { name }));
2839
+ return new Uint8Array(await subtle().wrapKey("raw", carrier, await webKey(wrappingKey, "wrapKey"), { name: name2 }));
2846
2840
  } catch {
2847
- throw fail2(operation, `${name} could not wrap with this key`);
2841
+ throw fail2(operation, `${name2} could not wrap with this key`);
2848
2842
  }
2849
2843
  }
2850
2844
  function jwkOf(operation, data) {
@@ -2863,25 +2857,25 @@ async function unwrapKey(formatValue, wrappedValue, unwrappingKeyValue, algorith
2863
2857
  const format2 = formatOf(operation, formatValue);
2864
2858
  const wrapped2 = bytesArgument(operation, wrappedValue, "wrappedKey");
2865
2859
  if (wrapped2.length > MAX_WRAPPED_BYTES) throw fail2(operation, `wrappedKey can be at most ${MAX_WRAPPED_BYTES} bytes, not ${wrapped2.length}`);
2866
- const { name, cipher } = wrapping(operation, algorithm);
2860
+ const { name: name2, cipher } = wrapping(operation, algorithm);
2867
2861
  const unwrappingKey = await keyOf(operation, unwrappingKeyValue);
2868
2862
  algorithmOf(operation, keyAlgorithm2, "importKey");
2869
2863
  extractableOf(operation, extractableValue);
2870
2864
  usagesOf(operation, usagesValue);
2871
- checkKey(operation, unwrappingKey, name, "unwrapKey");
2872
- requireType(operation, unwrappingKey, name === "RSA-OAEP" ? "private" : "secret");
2873
- if (name === "AES-KW") checkKeyWrap(operation, wrapped2);
2874
- else checkCipher(operation, name, cipher, wrapped2, unwrappingKey);
2865
+ checkKey(operation, unwrappingKey, name2, "unwrapKey");
2866
+ requireType(operation, unwrappingKey, name2 === "RSA-OAEP" ? "private" : "secret");
2867
+ if (name2 === "AES-KW") checkKeyWrap(operation, wrapped2);
2868
+ else checkCipher(operation, name2, cipher, wrapped2, unwrappingKey);
2875
2869
  let data;
2876
2870
  try {
2877
- if (name === "AES-KW") {
2878
- const carrier = await subtle().unwrapKey("raw", wrapped2, await webKey(unwrappingKey, "unwrapKey"), { name }, HMAC_CARRIER, true, ["sign"]);
2871
+ if (name2 === "AES-KW") {
2872
+ const carrier = await subtle().unwrapKey("raw", wrapped2, await webKey(unwrappingKey, "unwrapKey"), { name: name2 }, HMAC_CARRIER, true, ["sign"]);
2879
2873
  data = new Uint8Array(await subtle().exportKey("raw", carrier));
2880
2874
  } else {
2881
- data = new Uint8Array(await subtle().decrypt(webCipher(name, cipher), await webKey(unwrappingKey, "decrypt"), wrapped2));
2875
+ data = new Uint8Array(await subtle().decrypt(webCipher(name2, cipher), await webKey(unwrappingKey, "decrypt"), wrapped2));
2882
2876
  }
2883
2877
  } catch {
2884
- throw decryptionFailed(operation, name);
2878
+ throw decryptionFailed(operation, name2);
2885
2879
  }
2886
2880
  return importKeyAs(operation, format2, format2 === "jwk" ? jwkOf(operation, data) : data, keyAlgorithm2, extractableValue, usagesValue);
2887
2881
  }
@@ -2902,15 +2896,15 @@ function createSubtle() {
2902
2896
  };
2903
2897
  }
2904
2898
 
2905
- // plugins/host/krillplayer.ts
2899
+ // host/krillplayer.ts
2906
2900
  function userAddressesOf(manifest, parameters) {
2907
- return (manifest.parameters ?? []).flatMap(({ name, kind }) => kind === "url" && parameters[name] !== void 0 ? [parameters[name]] : []);
2901
+ return (manifest.parameters ?? []).flatMap(({ name: name2, kind }) => kind === "url" && parameters[name2] !== void 0 ? [parameters[name2]] : []);
2908
2902
  }
2909
2903
  function userHostsOf(manifest, parameters) {
2910
- return (manifest.parameters ?? []).flatMap(({ name, kind }) => {
2911
- if (kind !== "url" || parameters[name] === void 0) return [];
2904
+ return (manifest.parameters ?? []).flatMap(({ name: name2, kind }) => {
2905
+ if (kind !== "url" || parameters[name2] === void 0) return [];
2912
2906
  try {
2913
- const host = normalForm(parameters[name])?.host;
2907
+ const host = normalForm(parameters[name2])?.host;
2914
2908
  return host === void 0 ? [] : [host];
2915
2909
  } catch {
2916
2910
  return [];
@@ -2990,8 +2984,8 @@ function createGuides(now2 = Date.now) {
2990
2984
  scope({ pluginId, sourceId }) {
2991
2985
  const prefix = JSON.stringify([pluginId, sourceId]);
2992
2986
  return async (source, load) => {
2993
- const headers = Object.entries(source.headers ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2994
- const key = prefix + JSON.stringify([source.url, headers]);
2987
+ const headers2 = Object.entries(source.headers ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2988
+ const key = prefix + JSON.stringify([source.url, headers2]);
2995
2989
  const entry = entries.get(key);
2996
2990
  if (entry !== void 0 && entry.expiresAt > now2()) return entry.guide;
2997
2991
  const pending = loading.get(key) ?? fill2(key, source.maxAge ?? GUIDE_MAX_AGE_SECONDS, load);
@@ -3081,10 +3075,10 @@ function xmltvQuery(value) {
3081
3075
  }
3082
3076
  return query;
3083
3077
  }
3084
- async function loadGuide(fetch, network, grants, { url, headers }) {
3078
+ async function loadGuide(fetch, network, grants, { url, headers: headers2 }) {
3085
3079
  const { response } = await send(
3086
3080
  fetch,
3087
- { url, headers },
3081
+ { url, headers: headers2 },
3088
3082
  "guide",
3089
3083
  grants,
3090
3084
  network.lookup,
@@ -3112,16 +3106,16 @@ function createStorage() {
3112
3106
  return {
3113
3107
  get: (key) => entries().get(String(key)) ?? null,
3114
3108
  set(key, value) {
3115
- const name = String(key);
3109
+ const name2 = String(key);
3116
3110
  if (typeof value !== "string") throw new TypeError("krillplayer.storage only stores strings");
3117
- if (utf8Length(name) > STORAGE_LIMITS.keyBytes) throw new RangeError(`krillplayer.storage keys are at most ${STORAGE_LIMITS.keyBytes} bytes`);
3111
+ if (utf8Length(name2) > STORAGE_LIMITS.keyBytes) throw new RangeError(`krillplayer.storage keys are at most ${STORAGE_LIMITS.keyBytes} bytes`);
3118
3112
  if (utf8Length(value) > STORAGE_LIMITS.valueBytes) throw new RangeError(`krillplayer.storage values are at most ${STORAGE_LIMITS.valueBytes} bytes`);
3119
- const previous = entries().get(name);
3120
- const replaced = previous === void 0 ? 0 : utf8Length(name) + utf8Length(previous);
3121
- if (used() - replaced + utf8Length(name) + utf8Length(value) > STORAGE_LIMITS.pluginBytes) {
3113
+ const previous = entries().get(name2);
3114
+ const replaced = previous === void 0 ? 0 : utf8Length(name2) + utf8Length(previous);
3115
+ if (used() - replaced + utf8Length(name2) + utf8Length(value) > STORAGE_LIMITS.pluginBytes) {
3122
3116
  throw new RangeError(`krillplayer.storage is full: each plugin stores at most ${STORAGE_LIMITS.pluginBytes} bytes`);
3123
3117
  }
3124
- entries().set(name, value);
3118
+ entries().set(name2, value);
3125
3119
  },
3126
3120
  delete(key) {
3127
3121
  entries().delete(String(key));
@@ -3153,7 +3147,7 @@ function createKrillPlayer({
3153
3147
  const withheld = () => [
3154
3148
  ...credentialValues(current),
3155
3149
  ...handedKeys,
3156
- ...secrets.flatMap((name) => parameters !== null && Object.hasOwn(parameters, name) && parameters[name] !== "" ? [parameters[name]] : [])
3150
+ ...secrets.flatMap((name2) => parameters !== null && Object.hasOwn(parameters, name2) && parameters[name2] !== "" ? [parameters[name2]] : [])
3157
3151
  ];
3158
3152
  const grants = () => ({
3159
3153
  declared: network.hosts,
@@ -3217,8 +3211,8 @@ function createKrillPlayer({
3217
3211
  },
3218
3212
  parameters: { get: () => parameters === null ? null : { ...parameters } },
3219
3213
  appKeys: {
3220
- async get(name) {
3221
- const key = appKeyFor(appKeys, name);
3214
+ async get(name2) {
3215
+ const key = appKeyFor(appKeys, name2);
3222
3216
  if (key !== null) handedKeys.add(key);
3223
3217
  return key;
3224
3218
  }
@@ -3231,31 +3225,31 @@ function createKrillPlayer({
3231
3225
  error: pluginError
3232
3226
  };
3233
3227
  }
3234
- function appKeyFor(appKeys, name) {
3235
- if (typeof name !== "string" || name === "") throw new TypeError("krillplayer.appKeys.get takes a non-empty name");
3236
- if (appKeys === null || !appKeys.declared.includes(name) || !Object.hasOwn(appKeys.keys, name)) return null;
3237
- const key = appKeys.keys[name];
3228
+ function appKeyFor(appKeys, name2) {
3229
+ if (typeof name2 !== "string" || name2 === "") throw new TypeError("krillplayer.appKeys.get takes a non-empty name");
3230
+ if (appKeys === null || !appKeys.declared.includes(name2) || !Object.hasOwn(appKeys.keys, name2)) return null;
3231
+ const key = appKeys.keys[name2];
3238
3232
  return typeof key === "string" && key !== "" ? key : null;
3239
3233
  }
3240
3234
  function toBytes(data) {
3241
3235
  return typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
3242
3236
  }
3243
3237
  function responseHeaders(response, url) {
3244
- const headers = Object.fromEntries(response.headers);
3245
- delete headers["set-cookie"];
3238
+ const headers2 = Object.fromEntries(response.headers);
3239
+ delete headers2["set-cookie"];
3246
3240
  const host = new URL(url).hostname.toLowerCase();
3247
3241
  const cookies = response.headers.getSetCookie().filter((line) => {
3248
3242
  const attribute = line.split(";").slice(1).map((part) => part.trim()).find((part) => part.toLowerCase().startsWith("domain="));
3249
3243
  const domain = attribute?.slice("domain=".length).replace(/^\.+/, "").toLowerCase();
3250
3244
  return domain === void 0 || host === domain || host.endsWith(`.${domain}`);
3251
3245
  });
3252
- if (cookies.length > 0) headers["set-cookie"] = cookies.join("\n");
3253
- return headers;
3246
+ if (cookies.length > 0) headers2["set-cookie"] = cookies.join("\n");
3247
+ return headers2;
3254
3248
  }
3255
- async function send(fetch, { url, method = "GET", headers = {}, body }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
3249
+ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
3256
3250
  const bytes2 = body === void 0 ? void 0 : toBytes(body);
3257
3251
  const chain = new Chain(use, grants);
3258
- let pass = chain.first({ url, method, headers, body: bytes2 !== void 0 });
3252
+ let pass = chain.first({ url, method, headers: headers2, body: bytes2 !== void 0 });
3259
3253
  let target = url;
3260
3254
  for (; ; ) {
3261
3255
  const looked = pass.publicOnly === null ? void 0 : lookup2?.(pass.address.host);
@@ -3334,12 +3328,12 @@ async function decompress(format2, data, limit = FORMAT_LIMITS.decompressedBytes
3334
3328
  return output;
3335
3329
  }
3336
3330
  async function digest2(algorithm, data) {
3337
- const name = DIGESTS.get(algorithm.toLowerCase());
3338
- if (name === void 0) throw new TypeError(`unsupported digest ${algorithm}`);
3339
- return new Uint8Array(await crypto.subtle.digest(name, toBytes(data)));
3331
+ const name2 = DIGESTS.get(algorithm.toLowerCase());
3332
+ if (name2 === void 0) throw new TypeError(`unsupported digest ${algorithm}`);
3333
+ return new Uint8Array(await crypto.subtle.digest(name2, toBytes(data)));
3340
3334
  }
3341
3335
 
3342
- // plugins/contract/validate.ts
3336
+ // contract/validate.ts
3343
3337
  var UNKNOWN_KIND_HINTS = [
3344
3338
  [/^(video|vod|clip|short)s?$/i, "\u5E73\u53F0\u4E0A\u4E00\u4E2A\u666E\u901A\u7684\u89C6\u9891\u5199 onDemand\uFF0C\u4E0D\u8981\u5199\u6210 movie \u6216 file"],
3345
3339
  [/^(song|track|music|audio)s?$/i, 'NAS \u91CC\u7684\u97F3\u4E50\u6587\u4EF6\u5199 file\uFF0Cmedia \u4E3A "audio"\uFF0C\u9996\u53D1\u4E0D\u8BA4\u6210\u6B4C\u66F2'],
@@ -3440,23 +3434,23 @@ var Checker = class {
3440
3434
  object(schema, value, path, union2) {
3441
3435
  if (!isPlainObject(value)) return this.report(path, `is ${shown(value)}, expected ${describe(schema)}`);
3442
3436
  const kind = union2 === void 0 ? void 0 : value[union2.tag];
3443
- for (const [name, field] of Object.entries(schema.fields)) {
3444
- const present = value[name] !== void 0 && value[name] !== null;
3437
+ for (const [name2, field] of Object.entries(schema.fields)) {
3438
+ const present = value[name2] !== void 0 && value[name2] !== null;
3445
3439
  if (field.kind === "optional") {
3446
- if (present) this.check(field.of, value[name], `${path}.${name}`);
3440
+ if (present) this.check(field.of, value[name2], `${path}.${name2}`);
3447
3441
  } else if (!present) {
3448
- this.report(`${path}.${name}`, `is missing; ${schema.name} requires it`, `add ${name}: ${describe(field)}`);
3442
+ this.report(`${path}.${name2}`, `is missing; ${schema.name} requires it`, `add ${name2}: ${describe(field)}`);
3449
3443
  } else {
3450
- this.check(field, value[name], `${path}.${name}`);
3444
+ this.check(field, value[name2], `${path}.${name2}`);
3451
3445
  }
3452
3446
  }
3453
- for (const name of Object.keys(value).filter((key) => !Object.hasOwn(schema.fields, key))) {
3454
- if (value[name] === void 0) continue;
3455
- const owners = union2 === void 0 ? [] : Object.entries(union2.variants).filter(([, variant]) => variant.kind === "object" && Object.hasOwn(variant.fields, name)).map(([tag]) => tag);
3456
- const misplaced = MISPLACED_FIELD_HINTS.find((row) => row.kinds.includes(String(kind)) && row.fields.includes(name));
3447
+ for (const name2 of Object.keys(value).filter((key) => !Object.hasOwn(schema.fields, key))) {
3448
+ if (value[name2] === void 0) continue;
3449
+ const owners = union2 === void 0 ? [] : Object.entries(union2.variants).filter(([, variant]) => variant.kind === "object" && Object.hasOwn(variant.fields, name2)).map(([tag]) => tag);
3450
+ const misplaced = MISPLACED_FIELD_HINTS.find((row) => row.kinds.includes(String(kind)) && row.fields.includes(name2));
3457
3451
  const where = owners.length > 0 ? `; it belongs to ${owners.join(", ")}` : "";
3458
3452
  this.report(
3459
- `${path}.${name}`,
3453
+ `${path}.${name2}`,
3460
3454
  `is not a field of ${union2 === void 0 ? schema.name : `${union2.tag} ${JSON.stringify(kind)}`}${where}`,
3461
3455
  misplaced?.hint ?? (owners.length > 0 ? `pick the ${union2.tag} that has this field, or drop it` : `drop it; ${schema.name} has ${Object.keys(schema.fields).join(", ")}`)
3462
3456
  );
@@ -3469,18 +3463,18 @@ var Checker = class {
3469
3463
  if (typeof tag !== "string" || !Object.hasOwn(schema.variants, tag)) {
3470
3464
  return this.report(
3471
3465
  `${path}.${schema.tag}`,
3472
- `is ${shown(tag)}, expected one of ${known.map((name) => JSON.stringify(name)).join(", ")}; the App skips a ${schema.name} it does not recognize`,
3466
+ `is ${shown(tag)}, expected one of ${known.map((name2) => JSON.stringify(name2)).join(", ")}; the App skips a ${schema.name} it does not recognize`,
3473
3467
  hintFor(tag) ?? `pick a ${schema.tag} by the questions in choosing-a-kind.md of the krillplayer-plugin skill`
3474
3468
  );
3475
3469
  }
3476
3470
  const variant = schema.variants[tag];
3477
3471
  if (!schema.wrapped) return this.check(variant, value, path, schema);
3478
- for (const name of Object.keys(value)) {
3479
- if (name !== schema.tag && name !== tag && value[name] !== void 0) {
3472
+ for (const name2 of Object.keys(value)) {
3473
+ if (name2 !== schema.tag && name2 !== tag && value[name2] !== void 0) {
3480
3474
  this.report(
3481
- `${path}.${name}`,
3475
+ `${path}.${name2}`,
3482
3476
  `is not a field of ${schema.name}; a ${schema.tag} ${JSON.stringify(tag)} entry has only ${schema.tag} and ${tag}`,
3483
- Object.hasOwn(schema.variants, name) ? `set ${schema.tag}: ${JSON.stringify(name)}, or move the object under ${tag}` : "drop it"
3477
+ Object.hasOwn(schema.variants, name2) ? `set ${schema.tag}: ${JSON.stringify(name2)}, or move the object under ${tag}` : "drop it"
3484
3478
  );
3485
3479
  }
3486
3480
  }
@@ -3528,7 +3522,7 @@ function validateOutput(slot, fn, output) {
3528
3522
  return validate(expected.schema, output);
3529
3523
  }
3530
3524
 
3531
- // plugins/packer/zip.ts
3525
+ // packer/zip.ts
3532
3526
  import { crc32 } from "node:zlib";
3533
3527
  var DOS_DATE = 0 << 9 | 1 << 5 | 1;
3534
3528
  var UTF8_NAMES = 2048;
@@ -3536,8 +3530,8 @@ function writeZip(entries) {
3536
3530
  const locals = [];
3537
3531
  const centrals = [];
3538
3532
  let offset = 0;
3539
- for (const { name, data } of entries) {
3540
- const nameBytes = Buffer.from(name, "utf8");
3533
+ for (const { name: name2, data } of entries) {
3534
+ const nameBytes = Buffer.from(name2, "utf8");
3541
3535
  const crc = crc32(data);
3542
3536
  const local = Buffer.alloc(30);
3543
3537
  local.writeUInt32LE(67324752, 0);
@@ -3580,92 +3574,300 @@ function readZip(zip) {
3580
3574
  for (let index = 0; index < zip.readUInt16LE(end + 10); index += 1) {
3581
3575
  if (zip.readUInt32LE(position) !== 33639248) throw new Error("corrupt central directory");
3582
3576
  const nameLength = zip.readUInt16LE(position + 28);
3583
- const name = zip.toString("utf8", position + 46, position + 46 + nameLength);
3584
- if (zip.readUInt16LE(position + 10) !== 0) throw new Error(`${name} is compressed; plugin zips are stored only`);
3577
+ const name2 = zip.toString("utf8", position + 46, position + 46 + nameLength);
3578
+ if (zip.readUInt16LE(position + 10) !== 0) throw new Error(`${name2} is compressed; plugin zips are stored only`);
3585
3579
  const size = zip.readUInt32LE(position + 24);
3586
3580
  const local = zip.readUInt32LE(position + 42);
3587
3581
  const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
3588
3582
  const data = zip.subarray(start, start + size);
3589
- if (crc32(data) !== zip.readUInt32LE(position + 16)) throw new Error(`${name} fails its CRC`);
3590
- files2.set(name, data);
3583
+ if (crc32(data) !== zip.readUInt32LE(position + 16)) throw new Error(`${name2} fails its CRC`);
3584
+ files2.set(name2, data);
3591
3585
  position += 46 + nameLength + zip.readUInt16LE(position + 30) + zip.readUInt16LE(position + 32);
3592
3586
  }
3593
3587
  return files2;
3594
3588
  }
3595
3589
 
3596
- // plugins/trial-runner/cases.ts
3590
+ // trial-runner/cases.ts
3597
3591
  import { readdir, readFile as readFile2 } from "node:fs/promises";
3598
3592
  import { join, relative } from "node:path";
3599
3593
 
3600
- // plugins/trial-runner/credentials.ts
3594
+ // trial-runner/credentials.ts
3601
3595
  import { readFile } from "node:fs/promises";
3596
+
3597
+ // trial-runner/json-body.ts
3598
+ var NotJSON = class extends Error {
3599
+ };
3600
+ var BadJSON = class extends Error {
3601
+ };
3602
+ var JSON_DEPTH = 128;
3603
+ var NUMBER = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
3604
+ function parseJSONBody(text) {
3605
+ let index = 0;
3606
+ let depth = 0;
3607
+ const enter = () => {
3608
+ depth += 1;
3609
+ if (depth > JSON_DEPTH) throw new BadJSON(`nesting deeper than ${JSON_DEPTH}`);
3610
+ };
3611
+ const space = () => {
3612
+ while (index < text.length && " \n\r".includes(text[index])) index += 1;
3613
+ };
3614
+ const expect = (literal) => {
3615
+ if (!text.startsWith(literal, index)) throw new NotJSON();
3616
+ index += literal.length;
3617
+ };
3618
+ const string2 = () => {
3619
+ expect('"');
3620
+ let out = "";
3621
+ for (; ; ) {
3622
+ if (index >= text.length) throw new NotJSON();
3623
+ const char = text[index];
3624
+ const code = text.charCodeAt(index);
3625
+ if (char === '"') {
3626
+ index += 1;
3627
+ return out;
3628
+ }
3629
+ if (code < 32) throw new NotJSON();
3630
+ if (char !== "\\") {
3631
+ out += char;
3632
+ index += 1;
3633
+ continue;
3634
+ }
3635
+ const escape = text[index + 1];
3636
+ index += 2;
3637
+ const simple = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: " " };
3638
+ if (escape in simple) {
3639
+ out += simple[escape];
3640
+ continue;
3641
+ }
3642
+ if (escape !== "u" || !/^[0-9A-Fa-f]{4}$/.test(text.slice(index, index + 4))) throw new NotJSON();
3643
+ out += String.fromCharCode(parseInt(text.slice(index, index + 4), 16));
3644
+ index += 4;
3645
+ }
3646
+ };
3647
+ const value = () => {
3648
+ space();
3649
+ const char = text[index];
3650
+ if (char === "{") {
3651
+ index += 1;
3652
+ enter();
3653
+ const object2 = /* @__PURE__ */ new Map();
3654
+ space();
3655
+ if (text[index] === "}") {
3656
+ index += 1;
3657
+ depth -= 1;
3658
+ return object2;
3659
+ }
3660
+ for (; ; ) {
3661
+ space();
3662
+ const key = string2();
3663
+ space();
3664
+ expect(":");
3665
+ const entry = value();
3666
+ if (object2.has(key)) throw new BadJSON("duplicate key");
3667
+ object2.set(key, entry);
3668
+ space();
3669
+ if (text[index] === ",") {
3670
+ index += 1;
3671
+ continue;
3672
+ }
3673
+ expect("}");
3674
+ depth -= 1;
3675
+ return object2;
3676
+ }
3677
+ }
3678
+ if (char === "[") {
3679
+ index += 1;
3680
+ enter();
3681
+ const array2 = [];
3682
+ space();
3683
+ if (text[index] === "]") {
3684
+ index += 1;
3685
+ depth -= 1;
3686
+ return array2;
3687
+ }
3688
+ for (; ; ) {
3689
+ array2.push(value());
3690
+ space();
3691
+ if (text[index] === ",") {
3692
+ index += 1;
3693
+ continue;
3694
+ }
3695
+ expect("]");
3696
+ depth -= 1;
3697
+ return array2;
3698
+ }
3699
+ }
3700
+ if (char === '"') return string2();
3701
+ for (const [literal, result2] of [["true", true], ["false", false], ["null", null]]) {
3702
+ if (text.startsWith(literal, index)) {
3703
+ index += literal.length;
3704
+ return result2;
3705
+ }
3706
+ }
3707
+ NUMBER.lastIndex = index;
3708
+ const match = NUMBER.exec(text);
3709
+ if (match === null) throw new NotJSON();
3710
+ index += match[0].length;
3711
+ const number2 = Number(match[0]);
3712
+ if (!Number.isFinite(number2)) throw new BadJSON("number is not a finite double");
3713
+ return number2;
3714
+ };
3715
+ const result = value();
3716
+ space();
3717
+ if (index !== text.length) throw new NotJSON();
3718
+ const loneSurrogate = (item) => {
3719
+ if (typeof item === "string") return !item.isWellFormed();
3720
+ if (Array.isArray(item)) return item.some(loneSurrogate);
3721
+ if (item instanceof Map) return [...item].some(([key, entry]) => !key.isWellFormed() || loneSurrogate(entry));
3722
+ return false;
3723
+ };
3724
+ if (loneSurrogate(result)) throw new BadJSON("lone surrogate in a string");
3725
+ return result;
3726
+ }
3727
+ function bodyKind(bytes2) {
3728
+ if (bytes2 === null || bytes2.length === 0) return { kind: "none" };
3729
+ let text;
3730
+ try {
3731
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
3732
+ } catch {
3733
+ return { kind: "bytes", bytes: bytes2 };
3734
+ }
3735
+ if (text.startsWith("\uFEFF")) return { kind: "bad", reason: "starts with a byte order mark" };
3736
+ try {
3737
+ return { kind: "json", value: parseJSONBody(text) };
3738
+ } catch (error) {
3739
+ if (error instanceof BadJSON) return { kind: "bad", reason: error.message };
3740
+ if (error instanceof NotJSON) return { kind: "text", text };
3741
+ throw error;
3742
+ }
3743
+ }
3744
+ function canonicalJSON(value) {
3745
+ if (value instanceof Map) {
3746
+ return `{${[...value.keys()].sort().map((key) => `${JSON.stringify(key)}:${canonicalJSON(value.get(key))}`).join(",")}}`;
3747
+ }
3748
+ if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
3749
+ return JSON.stringify(value);
3750
+ }
3751
+ function writtenJSON(value) {
3752
+ if (value instanceof Map) return `{${[...value].map(([key, entry]) => `${JSON.stringify(key)}:${writtenJSON(entry)}`).join(",")}}`;
3753
+ if (Array.isArray(value)) return `[${value.map(writtenJSON).join(",")}]`;
3754
+ return JSON.stringify(value);
3755
+ }
3756
+ function redactedJSON(value, isSecretName2, redactString2) {
3757
+ if (typeof value === "string") return redactString2(value);
3758
+ if (Array.isArray(value)) return value.map((entry) => redactedJSON(entry, isSecretName2, redactString2));
3759
+ if (value instanceof Map) {
3760
+ return new Map([...value].map(([key, entry]) => [
3761
+ key,
3762
+ isSecretName2(key) && entry !== null && typeof entry !== "object" ? "REDACTED" : redactedJSON(entry, isSecretName2, redactString2)
3763
+ ]));
3764
+ }
3765
+ return value;
3766
+ }
3767
+
3768
+ // trial-runner/secret-names.ts
3769
+ var SECRET_HEADERS = ["cookie", "set-cookie", "authorization", "proxy-authorization", "x-csrf-token", "x-xsrf-token", "x-emby-token"];
3770
+ var SECRET_NAME_PATTERN = "^(?:access_?key|api_?key|access_?token|refresh_?token|id_?token|token|\\w+_token|subsonic_?token|sessdata|bili_jct|csrf|\\w*session\\w*|password|passwd|pw|secret|ticket|auth|authorization|cookie|dedeuserid|uin|openid|unionid)$";
3771
+ var SPACE = "\\x09\\x0A\\x0B\\x0C\\x0D\\x20";
3772
+ var QUERY_PATTERN = `^\\??[^=&${SPACE}?]+=[^&${SPACE}]*(?:&[^=&${SPACE}]+=[^&${SPACE}]*)+$`;
3773
+ var FORM_PATTERN = `^[^=&${SPACE}]+=[^&]*(?:&[^=&${SPACE}]+=[^&]*)*$`;
3774
+ var asciiLowercased = (value) => value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
3775
+ var headers = new Set(SECRET_HEADERS);
3776
+ var name = new RegExp(SECRET_NAME_PATTERN);
3777
+ var isSecretName = (value) => {
3778
+ const lower2 = asciiLowercased(value);
3779
+ return headers.has(lower2) || name.test(lower2);
3780
+ };
3781
+ var isSecretParam = (value, names) => isSecretName(value) || names.has("u") && (value === "t" && names.has("s") || value === "p");
3782
+
3783
+ // trial-runner/credentials.ts
3602
3784
  var REDACTED = "REDACTED";
3603
- var SECRET_HEADERS = /* @__PURE__ */ new Set(["cookie", "set-cookie", "authorization", "proxy-authorization", "x-csrf-token", "x-xsrf-token", "x-emby-token"]);
3604
- var SECRET_NAME = /^(?:access_?key|api_?key|access_?token|refresh_?token|id_?token|token|\w+_token|subsonic_?token|sessdata|bili_jct|csrf|\w*session\w*|password|passwd|pw|secret|ticket|auth|authorization|cookie|mid|dedeuserid|uin|openid|unionid)$/i;
3785
+ var REDACTED_TOKEN = "REDACTED-0000000000";
3786
+ var isRedacted = (value) => value === REDACTED || value === REDACTED_TOKEN;
3787
+ function fakeSecret(value) {
3788
+ return looksLikeToken(value) ? REDACTED_TOKEN : REDACTED;
3789
+ }
3790
+ function fakeValue(value, index) {
3791
+ return /^\d+$/.test(value) ? String(9 - index % 9).repeat(value.length) : fakeSecret(value);
3792
+ }
3793
+ var isFakeId = (value) => /^(\d)\1*$/.test(value);
3605
3794
  var SECRET_VALUES = [
3606
3795
  /\bSESSDATA=(?!REDACTED\b)[^;&\s"]{8,}/,
3607
3796
  /\bbili_jct=[0-9a-f]{16,}/i,
3608
- /\bBearer\s+[\w.~+/-]{16,}/,
3797
+ /\bBearer\s+(?!(?:REDACTED-0{10}|REDACTED)(?![\w.~+/-]))[\w.~+/-]{16,}/,
3609
3798
  /\beyJ[\w-]{8,}\.eyJ[\w-]{8,}\.[\w-]+/,
3610
- /\b(?:access_key|access_token)=[\w.-]{16,}/
3799
+ /\b(?:access_key|access_token)=(?!(?:REDACTED-0{10}|REDACTED)(?![\w.-]))[\w.-]{16,}/
3611
3800
  ];
3612
- var isSecretName = (name) => SECRET_HEADERS.has(name.toLowerCase()) || SECRET_NAME.test(name);
3613
- var isSubsonicSecret = (name, params) => params.has("u") && (name === "t" && params.has("s") || name === "p");
3614
- var isSecretParam = (name, params) => isSecretName(name) || isSubsonicSecret(name, params);
3615
3801
  var redactSetCookie = (lines) => lines.split("\n").map((line) => line.replace(/^([^=;]*)=[^;]*/, `$1=${REDACTED}`)).join("\n");
3616
3802
  var isRedactedSetCookie = (lines) => lines.split("\n").every((line) => new RegExp(`^[^=;]*=${REDACTED}(;|$)`).test(line));
3617
- function redactHeaders(headers) {
3618
- return Object.fromEntries(Object.entries(headers).flatMap(([name, value]) => {
3619
- if (name.toLowerCase() === "set-cookie") return [[name, redactSetCookie(value)]];
3620
- return isSecretName(name) ? [] : [[name, value]];
3803
+ function redactHeaders(headers2) {
3804
+ return Object.fromEntries(Object.entries(headers2).flatMap(([name2, value]) => {
3805
+ if (name2.toLowerCase() === "set-cookie") return [[name2, redactSetCookie(value)]];
3806
+ return isSecretName(name2) ? [] : [[name2, value]];
3621
3807
  }));
3622
3808
  }
3623
- function redactParams(params) {
3624
- let changed = false;
3625
- for (const name of new Set(params.keys())) {
3626
- if (isSecretParam(name, params)) {
3627
- params.set(name, REDACTED);
3628
- changed = true;
3629
- }
3809
+ var pairName = (pair) => {
3810
+ const raw = pair.split("=", 1)[0].replaceAll("+", " ");
3811
+ try {
3812
+ return decodeURIComponent(raw);
3813
+ } catch {
3814
+ return raw;
3630
3815
  }
3631
- return changed;
3816
+ };
3817
+ function redactPairs(text) {
3818
+ const pairs = text.split("&");
3819
+ const names = new Set(pairs.map(pairName));
3820
+ let changed = false;
3821
+ const rewritten = pairs.map((pair) => {
3822
+ const equals = pair.indexOf("=");
3823
+ if (!isSecretParam(pairName(pair), names) || equals >= 0 && pair.slice(equals + 1) === REDACTED) return pair;
3824
+ changed = true;
3825
+ return `${equals < 0 ? pair : pair.slice(0, equals)}=${REDACTED}`;
3826
+ });
3827
+ return changed ? rewritten.join("&") : text;
3632
3828
  }
3633
3829
  function redactUrl(url) {
3634
- const parsed = new URL(url);
3635
- return redactParams(parsed.searchParams) ? parsed.href : url;
3636
- }
3637
- var QUERY = /^\??[^=&\s?]+=[^&\s]*(?:&[^=&\s]+=[^&\s]*)+$/;
3830
+ const start = url.indexOf("?");
3831
+ if (start < 0) return url;
3832
+ const hash = url.indexOf("#");
3833
+ const end = hash < 0 ? url.length : hash;
3834
+ if (start > end) return url;
3835
+ return `${url.slice(0, start + 1)}${redactPairs(url.slice(start + 1, end))}${url.slice(end)}`;
3836
+ }
3837
+ var QUERY = new RegExp(QUERY_PATTERN);
3838
+ var FORM = new RegExp(FORM_PATTERN);
3638
3839
  function queryOf(value) {
3639
3840
  return QUERY.test(value) ? new URLSearchParams(value.replace(/^\?/, "")) : void 0;
3640
3841
  }
3641
3842
  function redactString(value) {
3642
- if (/^https?:\/\//.test(value) && URL.canParse(value)) return redactUrl(value);
3643
- const params = queryOf(value);
3644
- if (params === void 0 || !redactParams(params)) return value;
3645
- return `${value.startsWith("?") ? "?" : ""}${params.toString()}`;
3646
- }
3647
- function redactJSON(value) {
3648
- if (typeof value === "string") return redactString(value);
3649
- if (Array.isArray(value)) return value.map(redactJSON);
3650
- if (typeof value === "object" && value !== null) {
3651
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
3652
- key,
3653
- isSecretName(key) && entry !== null && typeof entry !== "object" ? REDACTED : redactJSON(entry)
3654
- ]));
3655
- }
3656
- return value;
3843
+ if (/^https?:\/\//.test(value)) return redactUrl(value);
3844
+ if (!QUERY.test(value)) return value;
3845
+ return value.startsWith("?") ? `?${redactPairs(value.slice(1))}` : redactPairs(value);
3657
3846
  }
3658
- var FORM = /^[^=&\s]+=[^&]*(?:&[^=&\s]+=[^&]*)*$/;
3659
3847
  function redactBody(body) {
3660
3848
  if (typeof body !== "string") return body;
3661
- try {
3662
- const parsed = JSON.parse(body);
3663
- const redacted = JSON.stringify(redactJSON(parsed));
3664
- return redacted === JSON.stringify(parsed) ? body : redacted;
3665
- } catch {
3666
- if (!FORM.test(body)) return body;
3667
- const params = new URLSearchParams(body);
3668
- return redactParams(params) ? params.toString() : body;
3849
+ const kind = bodyKind(bodyFromJSON(body));
3850
+ if (kind.kind === "json") {
3851
+ const redacted = redactedJSON(kind.value, isSecretName, redactString);
3852
+ return canonicalJSON(redacted) === canonicalJSON(kind.value) ? body : writtenJSON(redacted);
3853
+ }
3854
+ if (kind.kind === "text") return FORM.test(kind.text) ? redactPairs(kind.text) : body;
3855
+ return body;
3856
+ }
3857
+ var unmatchable = 0;
3858
+ function bodyKey(body) {
3859
+ const kind = bodyKind(bodyFromJSON(body));
3860
+ switch (kind.kind) {
3861
+ case "none":
3862
+ return "";
3863
+ case "bytes":
3864
+ return `bytes:${Buffer.from(kind.bytes).toString("base64")}`;
3865
+ case "bad":
3866
+ return `bad:${unmatchable += 1}`;
3867
+ case "json":
3868
+ return `json:${canonicalJSON(redactedJSON(kind.value, isSecretName, redactString))}`;
3869
+ case "text":
3870
+ return `text:${FORM.test(kind.text) ? redactPairs(kind.text) : kind.text}`;
3669
3871
  }
3670
3872
  }
3671
3873
  function redactExchange({ request, response }) {
@@ -3680,18 +3882,14 @@ function redactExchange({ request, response }) {
3680
3882
  }
3681
3883
  };
3682
3884
  }
3683
- function redactCredentials(credentials) {
3684
- if (typeof credentials !== "object" || credentials === null) return credentials;
3685
- return Object.fromEntries(Object.entries(credentials).map(([key]) => [key, REDACTED]));
3686
- }
3687
3885
  function findingsIn(value, path, findings) {
3688
3886
  if (typeof value === "string") {
3689
3887
  const text = value;
3690
3888
  if (SECRET_VALUES.some((pattern) => pattern.test(text))) findings.push(`${path}: credential-like value`);
3691
3889
  const query = /^https?:\/\//.test(text) && URL.canParse(text) ? new URL(text).searchParams : queryOf(text);
3692
3890
  if (query !== void 0) {
3693
- for (const [name, entry] of query) {
3694
- if (isSecretParam(name, query) && entry !== REDACTED && entry !== "") findings.push(`${path}: query parameter ${name}`);
3891
+ for (const [name2, entry] of query) {
3892
+ if (isSecretParam(name2, query) && !isRedacted(entry) && entry !== "") findings.push(`${path}: query parameter ${name2}`);
3695
3893
  }
3696
3894
  }
3697
3895
  return;
@@ -3707,7 +3905,7 @@ function findingsIn(value, path, findings) {
3707
3905
  return;
3708
3906
  }
3709
3907
  for (const [key, entry] of Object.entries(value)) {
3710
- const redacted = entry === REDACTED || key.toLowerCase() === "set-cookie" && typeof entry === "string" && isRedactedSetCookie(entry);
3908
+ const redacted = isRedacted(entry) || typeof entry === "string" && isFakeId(entry) || key.toLowerCase() === "set-cookie" && typeof entry === "string" && isRedactedSetCookie(entry);
3711
3909
  if (isSecretName(key) && typeof entry === "string" && !redacted && entry !== "") {
3712
3910
  findings.push(`${path}.${key}: ${key}`);
3713
3911
  }
@@ -3731,7 +3929,7 @@ async function scanDirectories(directories) {
3731
3929
  return { files: files2, findings };
3732
3930
  }
3733
3931
 
3734
- // plugins/trial-runner/cases.ts
3932
+ // trial-runner/cases.ts
3735
3933
  function bytesToJSON(bytes2) {
3736
3934
  return { $bytes: Buffer.from(bytes2).toString("base64") };
3737
3935
  }
@@ -3741,8 +3939,8 @@ function isBytesJSON(value) {
3741
3939
  function bodyToJSON(bytes2) {
3742
3940
  if (bytes2 === void 0 || bytes2.length === 0) return void 0;
3743
3941
  try {
3744
- const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
3745
- return /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text) ? bytesToJSON(bytes2) : text;
3942
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
3943
+ return /[\u0000-\u0008\u000b\u000c\u000e-\u001f\uFEFF]/.test(text) ? bytesToJSON(bytes2) : text;
3746
3944
  } catch {
3747
3945
  return bytesToJSON(bytes2);
3748
3946
  }
@@ -3787,11 +3985,11 @@ function requestOf(url, init) {
3787
3985
  return { method: init.method ?? "GET", url, ...body === void 0 ? {} : { body } };
3788
3986
  }
3789
3987
  function responseOf(response) {
3790
- const headers = Object.entries(response.headers).flatMap(([name, value]) => name.toLowerCase() === "set-cookie" ? value.split("\n").map((line) => [name, line]) : [[name, value]]);
3791
- return new Response(bodyFromJSON(response.body), { status: response.status, headers });
3988
+ const headers2 = Object.entries(response.headers).flatMap(([name2, value]) => name2.toLowerCase() === "set-cookie" ? value.split("\n").map((line) => [name2, line]) : [[name2, value]]);
3989
+ return new Response(bodyFromJSON(response.body), { status: response.status, headers: headers2 });
3792
3990
  }
3793
- var canonicalHeaders = (headers) => JSON.stringify(Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
3794
- var requestKey = ({ method, url, body }) => `${method} ${url} ${Buffer.from(bodyFromJSON(body) ?? []).toString("base64")}`;
3991
+ var canonicalHeaders = (headers2) => JSON.stringify(Object.entries(headers2 ?? {}).map(([name2, value]) => [name2.toLowerCase(), value]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
3992
+ var requestKey = ({ method, url, body }) => `${method} ${url} ${bodyKey(body)}`;
3795
3993
  function replayFetch(exchanges) {
3796
3994
  const pending = [...exchanges];
3797
3995
  const unrecorded = [];
@@ -3815,32 +4013,38 @@ function replayFetch(exchanges) {
3815
4013
  var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
3816
4014
  function recordingFetch(fetch) {
3817
4015
  const exchanges = [];
4016
+ const unacceptable = [];
3818
4017
  const record = async (url, init) => {
4018
+ const sent = requestOf(url, init);
4019
+ const kind = bodyKind(bodyFromJSON(sent.body));
4020
+ if (kind.kind === "bad") unacceptable.push(`request ${exchanges.length + 1} (${sent.method}): ${kind.reason}`);
3819
4021
  const response = await fetch(url, init);
3820
4022
  const body = bodyToJSON(new Uint8Array(await response.arrayBuffer()));
3821
4023
  const recorded = {
3822
4024
  status: response.status,
3823
- headers: Object.fromEntries(Object.entries(responseHeaders(response, url)).filter(([name]) => !TRANSPORT_HEADERS.has(name))),
4025
+ headers: Object.fromEntries(Object.entries(responseHeaders(response, url)).filter(([name2]) => !TRANSPORT_HEADERS.has(name2))),
3824
4026
  ...body === void 0 ? {} : { body }
3825
4027
  };
3826
4028
  exchanges.push(redactExchange({ request: requestOf(url, init), response: recorded }));
3827
4029
  return responseOf(recorded);
3828
4030
  };
3829
- return { fetch: record, exchanges };
4031
+ return { fetch: record, exchanges, unacceptable };
3830
4032
  }
3831
4033
  async function jsonFiles(directory) {
3832
4034
  const entries = await readdir(directory, { recursive: true, withFileTypes: true });
3833
4035
  return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.parentPath.includes("node_modules")).map((entry) => join(entry.parentPath, entry.name)).sort();
3834
4036
  }
4037
+ var BYTE_ORDER_MARK_IN_CASE = "case file holds U+FEFF, which the Swift kernel's JSON reader drops; keep such text as $bytes";
4038
+ var holdsByteOrderMark = (raw) => raw.includes("\uFEFF") || /\\u[fF][eE][fF][fF]/.test(raw);
3835
4039
  async function readCases(directory) {
3836
4040
  const files2 = await jsonFiles(directory);
3837
- return Promise.all(files2.map(async (file) => ({
3838
- name: relative(directory, file),
3839
- data: JSON.parse(await readFile2(file, "utf8"))
3840
- })));
4041
+ return Promise.all(files2.map(async (file) => {
4042
+ const raw = await readFile2(file, "utf8");
4043
+ return { name: relative(directory, file), data: JSON.parse(raw), byteOrderMark: holdsByteOrderMark(raw) };
4044
+ }));
3841
4045
  }
3842
4046
 
3843
- // plugins/trial-runner/engine.ts
4047
+ // trial-runner/engine.ts
3844
4048
  import { execFile, spawn } from "node:child_process";
3845
4049
  import { createHash } from "node:crypto";
3846
4050
  import { constants } from "node:fs";
@@ -3851,7 +4055,7 @@ import { dirname, join as join2, relative as relative2 } from "node:path";
3851
4055
  import { fileURLToPath } from "node:url";
3852
4056
  import { promisify } from "node:util";
3853
4057
 
3854
- // plugins/host/globals.ts
4058
+ // host/globals.ts
3855
4059
  var ECMASCRIPT_GLOBALS = [
3856
4060
  "globalThis",
3857
4061
  "Infinity",
@@ -3916,7 +4120,7 @@ var ECMASCRIPT_GLOBALS = [
3916
4120
  var HOST_GLOBALS = ["TextEncoder", "TextDecoder", "console"];
3917
4121
  var PLUGIN_GLOBALS = /* @__PURE__ */ new Set([...ECMASCRIPT_GLOBALS, ...HOST_GLOBALS]);
3918
4122
 
3919
- // plugins/trial-runner/wire.ts
4123
+ // trial-runner/wire.ts
3920
4124
  var MARKER = "\0";
3921
4125
  function encode(value) {
3922
4126
  const parts = [];
@@ -3954,12 +4158,12 @@ function decode(json, blob) {
3954
4158
  if (Array.isArray(item)) return item.map(revive);
3955
4159
  const names = Object.keys(item);
3956
4160
  if (names.length === 1 && names[0] === MARKER) return parts[item[MARKER]];
3957
- return Object.fromEntries(names.map((name) => [name, revive(item[name])]));
4161
+ return Object.fromEntries(names.map((name2) => [name2, revive(item[name2])]));
3958
4162
  };
3959
4163
  return revive(message);
3960
4164
  }
3961
4165
 
3962
- // plugins/trial-runner/engine.ts
4166
+ // trial-runner/engine.ts
3963
4167
  var here = dirname(fileURLToPath(import.meta.url));
3964
4168
  var run3 = promisify(execFile);
3965
4169
  var KERNEL_LIMITS = {
@@ -4004,7 +4208,7 @@ async function executable(file) {
4004
4208
  return false;
4005
4209
  }
4006
4210
  }
4007
- var environment = (name) => process.env[name] || void 0;
4211
+ var environment = (name2) => process.env[name2] || void 0;
4008
4212
  async function build() {
4009
4213
  const quickjs = join2(kernelDirectory(), "Sources/CQuickJS");
4010
4214
  const compiler = environment("CC") ?? "cc";
@@ -4065,7 +4269,7 @@ var prelude;
4065
4269
  function preludeSource() {
4066
4270
  const path = join2(kernelDirectory(), "Sources/Kernel/PluginPrelude.js");
4067
4271
  prelude ??= readFile3(path, "utf8").then(
4068
- (template) => template.replaceAll("__GLOBALS__", `[${[...PLUGIN_GLOBALS].sort().map((name) => JSON.stringify(name)).join(", ")}]`),
4272
+ (template) => template.replaceAll("__GLOBALS__", `[${[...PLUGIN_GLOBALS].sort().map((name2) => JSON.stringify(name2)).join(", ")}]`),
4069
4273
  (error) => {
4070
4274
  throw new EngineFailure(`could not read the plugin prelude ${path}: ${error.message}`);
4071
4275
  }
@@ -4227,12 +4431,12 @@ var CALLS = {
4227
4431
  };
4228
4432
  var STARTS = {
4229
4433
  "http.request": (k, [request]) => k.http.request(request),
4230
- "appKeys.get": (k, [name]) => k.appKeys.get(name),
4434
+ "appKeys.get": (k, [name2]) => k.appKeys.get(name2),
4231
4435
  "formats.xmltv.channels": (k, [source]) => k.formats.xmltv.channels(source),
4232
4436
  "formats.xmltv.programmes": (k, [source, query]) => k.formats.xmltv.programmes(source, query),
4233
4437
  "metadata.search": (k, [kind, query, options]) => k.metadata.search(kind, query, options),
4234
4438
  "metadata.get": (k, [kind, ids]) => k.metadata.get(kind, ids),
4235
- "metadata.list": (k, [name, kind, options]) => k.metadata.list(name, kind, options),
4439
+ "metadata.list": (k, [name2, kind, options]) => k.metadata.list(name2, kind, options),
4236
4440
  "files.list": (k, [path, cursor]) => k.files.list(path, cursor ?? void 0),
4237
4441
  "files.stat": (k, [path]) => k.files.stat(path),
4238
4442
  "files.read": (k, [path, offset, length]) => k.files.read(path, offset, length)
@@ -4349,15 +4553,15 @@ var EngineContext = class _EngineContext {
4349
4553
  this.#settled.set(message.call, message.ok === true ? { ok: true, value: message.value ?? null } : { ok: false, error: failure(message) });
4350
4554
  return null;
4351
4555
  }
4352
- const name = String(message.name);
4353
- const capability = name.split(".")[0];
4556
+ const name2 = String(message.name);
4557
+ const capability = name2.split(".")[0];
4354
4558
  if (this.#slot === "status" && !STATUS_SLOT_CAPABILITIES.has(capability)) {
4355
4559
  throw new TypeError(`krillplayer.${capability} is not available to the status slot`);
4356
4560
  }
4357
- if (message.op === "start" && Object.hasOwn(STARTS, name)) {
4561
+ if (message.op === "start" && Object.hasOwn(STARTS, name2)) {
4358
4562
  const id = Number(message.id);
4359
4563
  this.#inFlight += 1;
4360
- STARTS[name](this.#krillplayer, args).then(
4564
+ STARTS[name2](this.#krillplayer, args).then(
4361
4565
  (value) => this.#complete({ id, ok: true, value }),
4362
4566
  (error) => this.#complete({
4363
4567
  id,
@@ -4368,8 +4572,8 @@ var EngineContext = class _EngineContext {
4368
4572
  );
4369
4573
  return null;
4370
4574
  }
4371
- if (message.op === "call" && Object.hasOwn(CALLS, name)) return await CALLS[name](this.#krillplayer, args) ?? null;
4372
- throw new TypeError(`malformed message from the plugin context: ${message.op} ${name}`);
4575
+ if (message.op === "call" && Object.hasOwn(CALLS, name2)) return await CALLS[name2](this.#krillplayer, args) ?? null;
4576
+ throw new TypeError(`malformed message from the plugin context: ${message.op} ${name2}`);
4373
4577
  }
4374
4578
  #complete(completion) {
4375
4579
  this.#completions.push(completion);
@@ -4385,7 +4589,7 @@ function structuredError(error) {
4385
4589
  return error instanceof PluginFailure ? error.plugin : { kind: "other" };
4386
4590
  }
4387
4591
 
4388
- // plugins/trial-runner/files.ts
4592
+ // trial-runner/files.ts
4389
4593
  var FAILURES = { loginRequired: "accessDenied", retryable: "unreachable" };
4390
4594
  function scriptedFiles(script = {}) {
4391
4595
  const problems = [];
@@ -4429,8 +4633,8 @@ function scriptedFiles(script = {}) {
4429
4633
  return node;
4430
4634
  };
4431
4635
  const content = (node) => new Uint8Array(bodyFromJSON(node.file.content) ?? []);
4432
- const entry = (name, path, node) => ({
4433
- name,
4636
+ const entry = (name2, path, node) => ({
4637
+ name: name2,
4434
4638
  path,
4435
4639
  isDirectory: node.directory,
4436
4640
  ...node.directory ? {} : { size: node.file.size ?? content(node).length },
@@ -4448,7 +4652,7 @@ function scriptedFiles(script = {}) {
4448
4652
  const start = Number(cursor ?? "0");
4449
4653
  const end = script.pageSize === void 0 ? names.length : start + script.pageSize;
4450
4654
  return {
4451
- entries: names.slice(start, end).map((name) => entry(name, path === "" ? name : `${path}/${name}`, node.children.get(name))),
4655
+ entries: names.slice(start, end).map((name2) => entry(name2, path === "" ? name2 : `${path}/${name2}`, node.children.get(name2))),
4452
4656
  ...end < names.length ? { next: String(end) } : {}
4453
4657
  };
4454
4658
  },
@@ -4466,7 +4670,7 @@ function scriptedFiles(script = {}) {
4466
4670
  return { service, problems: () => [...problems] };
4467
4671
  }
4468
4672
 
4469
- // plugins/trial-runner/metadata.ts
4673
+ // trial-runner/metadata.ts
4470
4674
  function scriptedMetadata(script = []) {
4471
4675
  const pending = [...script];
4472
4676
  const problems = [];
@@ -4517,9 +4721,9 @@ function scriptedMetadata(script = []) {
4517
4721
  const found = validate(Work, reply, "reply");
4518
4722
  return found.length > 0 ? malformed(`scripted metadata reply is not a Work: ${found.join("; ")}`) : work(reply);
4519
4723
  },
4520
- async list(name, kind, filter, cursor) {
4521
- checkList(name, kind, filter);
4522
- return page(answer({ call: "list", name, kind, ...optional3({ ...filter, cursor }) }));
4724
+ async list(name2, kind, filter, cursor) {
4725
+ checkList(name2, kind, filter);
4726
+ return page(answer({ call: "list", name: name2, kind, ...optional3({ ...filter, cursor }) }));
4523
4727
  }
4524
4728
  };
4525
4729
  return {
@@ -4532,12 +4736,100 @@ function optional3(fields) {
4532
4736
  return Object.fromEntries(Object.entries(fields).filter((entry) => entry[1] !== void 0));
4533
4737
  }
4534
4738
 
4535
- // plugins/trial-runner/static-check.ts
4739
+ // trial-runner/capabilities.ts
4740
+ function inheritedFunctions(slot, functions) {
4741
+ const inherited = /* @__PURE__ */ new Set();
4742
+ for (let prototype = Object.getPrototypeOf(slot); prototype !== null; prototype = Object.getPrototypeOf(prototype)) {
4743
+ for (const member of Object.getOwnPropertyNames(prototype)) {
4744
+ if (functions.includes(member) && !Object.hasOwn(slot, member)) inherited.add(member);
4745
+ }
4746
+ }
4747
+ return [...inherited];
4748
+ }
4749
+ function capabilitiesOf(namespace) {
4750
+ const problems = [];
4751
+ const found = /* @__PURE__ */ new Set();
4752
+ for (const [name2, value] of Object.entries(namespace)) {
4753
+ const top = TOP_LEVEL_FUNCTIONS[name2];
4754
+ if (top !== void 0) {
4755
+ if (typeof value === "function") found.add(top);
4756
+ else problems.push(`${name2} must be a function`);
4757
+ continue;
4758
+ }
4759
+ const rule = SLOT_RULES[name2];
4760
+ if (rule === void 0) {
4761
+ problems.push(`exports ${name2}; plugins export only ${[...Object.keys(SLOT_RULES), ...Object.keys(TOP_LEVEL_FUNCTIONS)].join(", ")}`);
4762
+ continue;
4763
+ }
4764
+ if (typeof value !== "object" || value === null) {
4765
+ problems.push(`${name2} must be an object of functions`);
4766
+ continue;
4767
+ }
4768
+ const has = (member) => typeof slotMember(value, member) === "function";
4769
+ for (const member of Object.getOwnPropertyNames(value)) {
4770
+ if (!rule.functions.includes(member)) problems.push(`${name2}.${member} is not in the contract (${rule.functions.join(", ")})`);
4771
+ else if (!has(member)) problems.push(`${name2}.${member} must be a function`);
4772
+ }
4773
+ for (const member of inheritedFunctions(value, rule.functions)) {
4774
+ problems.push(`${name2}.${member} is inherited; slot functions must be the object's own properties (an object literal, not a class instance)`);
4775
+ }
4776
+ for (const member of rule.required) if (!has(member)) problems.push(`${name2} needs ${member}`);
4777
+ for (const [first, second] of rule.pairs) {
4778
+ if (has(first) !== has(second)) {
4779
+ const [present, missing] = has(first) ? [first, second] : [second, first];
4780
+ problems.push(`${name2}.${present} needs ${name2}.${missing}`);
4781
+ }
4782
+ }
4783
+ const matched = Object.entries(rule.capabilities).filter(([, any]) => any.some(has)).map(([capability]) => capability);
4784
+ const superseded = new Set(matched.flatMap((capability) => rule.supersedes?.[capability] ?? []));
4785
+ const generated = matched.filter((capability) => !superseded.has(capability));
4786
+ generated.forEach((capability) => found.add(capability));
4787
+ const all = Object.values(rule.capabilities).flat();
4788
+ if (all.length > 0 && generated.length === 0) problems.push(`${name2} needs one of ${all.join(", ")}`);
4789
+ }
4790
+ return { capabilities: Capability.values.filter((name2) => found.has(name2)), problems };
4791
+ }
4792
+
4793
+ // trial-runner/sandbox.ts
4794
+ import vm from "node:vm";
4795
+ var UTF8_LABELS = /* @__PURE__ */ new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]);
4796
+ var Utf8TextDecoder = class extends TextDecoder {
4797
+ constructor(label = "utf-8", options) {
4798
+ if (!UTF8_LABELS.has(String(label).trim().toLowerCase())) {
4799
+ throw new RangeError(`TextDecoder only supports utf-8, not ${label}`);
4800
+ }
4801
+ super("utf-8", options);
4802
+ }
4803
+ };
4804
+ async function loadPlugin(source, { identifier, allowCodeGeneration }) {
4805
+ const context = vm.createContext({}, { codeGeneration: { strings: allowCodeGeneration, wasm: false } });
4806
+ const remaining = vm.runInContext(`(() => {
4807
+ const allowed = new Set(${JSON.stringify([...PLUGIN_GLOBALS])});
4808
+ for (const name of Object.getOwnPropertyNames(globalThis)) if (!allowed.has(name)) delete globalThis[name];
4809
+ return Object.getOwnPropertyNames(globalThis).filter((name) => !allowed.has(name));
4810
+ })()`, context);
4811
+ if (remaining.length > 0) throw new Error(`could not remove globals: ${remaining.join(", ")}`);
4812
+ const global = vm.runInContext("globalThis", context);
4813
+ const silent = () => {
4814
+ };
4815
+ const consoleObject = Object.freeze({ debug: silent, trace: silent, log: silent, info: silent, warn: silent, error: silent });
4816
+ for (const [name2, value] of [["TextEncoder", TextEncoder], ["TextDecoder", Utf8TextDecoder], ["console", consoleObject]]) {
4817
+ Object.defineProperty(global, name2, { value, writable: true, configurable: true });
4818
+ }
4819
+ const module = new vm.SourceTextModule(source, { context, identifier });
4820
+ await module.link(() => {
4821
+ throw new Error("plugins cannot import modules");
4822
+ });
4823
+ await module.evaluate();
4824
+ return module.namespace;
4825
+ }
4826
+
4827
+ // trial-runner/static-check.ts
4536
4828
  import { Linter } from "eslint";
4537
4829
  var globalsRule = {
4538
4830
  create(context) {
4539
- const reportName = (node, name) => {
4540
- if (!PLUGIN_GLOBALS.has(name)) context.report({ node, message: `global ${name} is not in the plugin globals allowlist` });
4831
+ const reportName = (node, name2) => {
4832
+ if (!PLUGIN_GLOBALS.has(name2)) context.report({ node, message: `global ${name2} is not in the plugin globals allowlist` });
4541
4833
  };
4542
4834
  return {
4543
4835
  MemberExpression(node) {
@@ -4581,53 +4873,61 @@ var RESERVED_PARAMETER_PREFIX = "krillplayer.files.";
4581
4873
  function checkManifest(manifest) {
4582
4874
  const parameters = Array.isArray(manifest.parameters) ? manifest.parameters : [];
4583
4875
  const problems = [];
4876
+ if (manifest.loginRequired === true && Array.isArray(manifest.capabilities) && !manifest.capabilities.includes("login")) {
4877
+ problems.push("loginRequired needs a login slot: export login so the user can log in when adding a source, or drop loginRequired");
4878
+ }
4879
+ for (const parameter of parameters) {
4880
+ if (typeof parameter !== "object" || parameter === null || parameter.perSource === void 0) continue;
4881
+ problems.push(`parameter ${String(parameter.name)} sets perSource, which only applies to settings: instance parameters already belong to one source`);
4882
+ }
4584
4883
  for (const parameter of parameters) {
4585
4884
  if (typeof parameter !== "object" || parameter === null) continue;
4586
- const { name, dependsOn, visibleWhen } = parameter;
4885
+ const { name: name2, dependsOn, visibleWhen } = parameter;
4587
4886
  const used = [
4588
- ["declares", name],
4887
+ ["declares", name2],
4589
4888
  ...(Array.isArray(dependsOn) ? dependsOn : []).map((item) => ["depends on", item]),
4590
4889
  ...(Array.isArray(visibleWhen) ? visibleWhen : []).map((item) => ["is shown by", item?.name])
4591
4890
  ];
4592
4891
  for (const [how, reserved] of used) {
4593
4892
  if (typeof reserved === "string" && reserved.startsWith(RESERVED_PARAMETER_PREFIX)) {
4594
- problems.push(`parameter ${String(name)} ${how} ${reserved}: names starting with ${RESERVED_PARAMETER_PREFIX} are reserved by the app, which asks the user for the file server itself and never shows those values to a plugin`);
4893
+ problems.push(`parameter ${String(name2)} ${how} ${reserved}: names starting with ${RESERVED_PARAMETER_PREFIX} are reserved by the app, which asks the user for the file server itself and never shows those values to a plugin`);
4595
4894
  }
4596
4895
  }
4597
4896
  }
4598
4897
  return problems;
4599
4898
  }
4600
4899
 
4601
- // plugins/trial-runner/trial.ts
4900
+ // trial-runner/trial.ts
4602
4901
  async function readFiles(path) {
4603
4902
  const entries = path.endsWith(".zip") ? [...readZip(await readFile4(path))] : await (async () => {
4604
- const locales = (await readdir3(join3(path, LOCALES)).catch(() => [])).filter((name) => name.endsWith(".json")).map((name) => `${LOCALES}/${name}`);
4605
- const names = [...(await readdir3(path)).filter((name) => /\.m?js$/.test(name) || name === "manifest.json"), ...locales];
4606
- return Promise.all(names.map(async (name) => [name, await readFile4(join3(path, name))]));
4903
+ const locales = (await readdir3(join3(path, LOCALES)).catch(() => [])).filter((name2) => name2.endsWith(".json")).map((name2) => `${LOCALES}/${name2}`);
4904
+ const names = [...(await readdir3(path)).filter((name2) => /\.m?js$/.test(name2) || name2 === "manifest.json"), ...locales];
4905
+ return Promise.all(names.map(async (name2) => [name2, await readFile4(join3(path, name2))]));
4607
4906
  })();
4608
- return new Map(entries.map(([name, data]) => {
4609
- if (!name.endsWith(".json")) return [name, Buffer.from(data).toString("utf8")];
4907
+ return new Map(entries.map(([name2, data]) => {
4908
+ if (!name2.endsWith(".json")) return [name2, Buffer.from(data).toString("utf8")];
4610
4909
  const text = pluginJSONText(data);
4611
4910
  if (text === void 0 || nestedTooDeep(text)) {
4612
- throw new Error(`${name} in ${path} must be UTF-8 JSON without a byte order mark or NUL, nested at most ${VALUE_LIMITS.depth} levels`);
4911
+ throw new Error(`${name2} in ${path} must be UTF-8 JSON without a byte order mark or NUL, nested at most ${VALUE_LIMITS.depth} levels`);
4613
4912
  }
4614
- return [name, text];
4913
+ return [name2, text];
4615
4914
  }));
4616
4915
  }
4617
4916
  var LOCALES = "locales";
4618
4917
  function dictionariesIn(files2) {
4619
- return Object.fromEntries([...files2].flatMap(([name, text]) => {
4620
- const match = /^locales\/([^/]+)\.json$/.exec(name);
4918
+ return Object.fromEntries([...files2].flatMap(([name2, text]) => {
4919
+ const match = /^locales\/([^/]+)\.json$/.exec(name2);
4621
4920
  return match === null ? [] : [[match[1], JSON.parse(text)]];
4622
4921
  }));
4623
4922
  }
4624
4923
  async function readPlugin(path) {
4625
4924
  const files2 = await readFiles(path);
4626
- const scripts = [...files2.keys()].filter((name) => /\.m?js$/.test(name));
4925
+ const scripts = [...files2.keys()].filter((name2) => /\.m?js$/.test(name2));
4627
4926
  if (scripts.length !== 1) throw new Error(`${path} must contain exactly one bundled .js file, found ${scripts.length}`);
4628
4927
  const manifest = JSON.parse(files2.get("manifest.json") ?? "{}");
4629
4928
  const source = files2.get(scripts[0]);
4630
4929
  const checked = checkPlugin(source);
4930
+ const capabilities = Array.isArray(manifest.capabilities) || checked.violations.length > 0 ? manifest.capabilities : await loadPlugin(source, { identifier: join3(path, scripts[0]), allowCodeGeneration: !checked.exports.includes("status") }).then((namespace) => capabilitiesOf(namespace).capabilities, () => void 0);
4631
4931
  return {
4632
4932
  id: manifest.id ?? basename(resolve(path)),
4633
4933
  file: join3(path, scripts[0]),
@@ -4641,7 +4941,7 @@ async function readPlugin(path) {
4641
4941
  dictionaries: dictionariesIn(files2),
4642
4942
  exports: checked.exports,
4643
4943
  // 清单用了内核留用的参数名(contract.md 6.1)和静态检查拦下的一样判红。
4644
- violations: [...checked.violations, ...checkManifest(manifest).map((problem) => ` manifest.json: ${problem}`)]
4944
+ violations: [...checked.violations, ...checkManifest({ ...manifest, capabilities }).map((problem) => ` manifest.json: ${problem}`)]
4645
4945
  };
4646
4946
  }
4647
4947
  var TRIAL_CAPABILITIES = new Set(Object.keys(createKrillPlayer({
@@ -4746,9 +5046,9 @@ async function runSlotCase(plugin2, testCase) {
4746
5046
  }
4747
5047
  function report(results, log) {
4748
5048
  const counts = { passed: 0, skipped: 0, failed: 0 };
4749
- for (const { name, outcome } of results) {
5049
+ for (const { name: name2, outcome } of results) {
4750
5050
  counts[outcome.status] += 1;
4751
- log(outcome.status === "passed" ? `PASS ${name}` : `${outcome.status === "skipped" ? "SKIP" : "FAIL"} ${name}
5051
+ log(outcome.status === "passed" ? `PASS ${name2}` : `${outcome.status === "skipped" ? "SKIP" : "FAIL"} ${name2}
4752
5052
  ${outcome.reason}`);
4753
5053
  }
4754
5054
  log(`passed ${counts.passed} skipped ${counts.skipped} failed ${counts.failed}`);
@@ -4760,7 +5060,9 @@ async function runCommand(pluginDirectory, casesDirectory, log) {
4760
5060
  for (const violation of plugin2.violations) log(`STATIC ${plugin2.file}:${violation}`);
4761
5061
  const cases = await readCases(casesDirectory);
4762
5062
  const results = [];
4763
- for (const { name, data } of cases) results.push({ name, outcome: await runSlotCase(plugin2, data) });
5063
+ for (const { name: name2, data, byteOrderMark } of cases) {
5064
+ results.push({ name: name2, outcome: byteOrderMark ? { status: "failed", reason: BYTE_ORDER_MARK_IN_CASE } : await runSlotCase(plugin2, data) });
5065
+ }
4764
5066
  return report(results, log) && plugin2.violations.length === 0;
4765
5067
  }
4766
5068
  var RecordRefused = class extends Error {
@@ -4783,40 +5085,138 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
4783
5085
  return { output: toJSON(value) };
4784
5086
  };
4785
5087
  await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials));
4786
- const redacted = credentials === null ? null : redactCredentials(credentials);
5088
+ const own = credentials === null ? [] : Object.values(credentials).filter((value) => typeof value === "string" && value !== "").map((value, index) => ({ value, fake: fakeValue(value, index) }));
5089
+ const redacted = credentials === null ? null : Object.fromEntries(Object.entries(credentials).map(([key, value]) => [key, typeof value === "string" ? withOwnValuesReplaced(value, own) : REDACTED]));
5090
+ const keptArgs = withOwnValuesReplaced(args, own);
4787
5091
  const secret = new Set(plugin2.parameters.filter((parameter) => parameter.secret).map((parameter) => parameter.name));
4788
- const kept = parameters === void 0 ? void 0 : Object.fromEntries(Object.entries(parameters).map(([name, value]) => [name, secret.has(name) ? REDACTED : value]));
4789
- const keptKeys = appKeys === void 0 ? void 0 : Object.fromEntries(Object.keys(appKeys).map((name) => [name, REDACTED]));
4790
- const exchanges = withoutValues(recording.exchanges, Object.values(appKeys ?? {}).filter((key) => key !== ""));
5092
+ const kept = parameters === void 0 ? void 0 : Object.fromEntries(Object.entries(parameters).map(([name2, value]) => [name2, secret.has(name2) ? fakeSecret(value) : value]));
5093
+ const keptKeys = appKeys === void 0 ? void 0 : Object.fromEntries(Object.entries(appKeys).map(([name2, key]) => [name2, fakeSecret(key)]));
5094
+ const exchanges = withOwnValuesReplaced(
5095
+ withoutValues(recording.exchanges, Object.values(appKeys ?? {}).filter((key) => key !== "")),
5096
+ own
5097
+ );
5098
+ const unacceptable = [...recording.unacceptable, ...exchanges.flatMap(({ request }) => {
5099
+ const kind = bodyKind(bodyFromJSON(request.body));
5100
+ return kind.kind === "bad" ? [`${request.method} ${request.url}: ${kind.reason}`] : [];
5101
+ })];
5102
+ if (unacceptable.length > 0) throw new RecordRefused(`a request body cannot be replayed the same way on both runners, nothing was recorded:
5103
+ ${unacceptable.join("\n ")}`);
4791
5104
  const replay = replayFetch(exchanges);
4792
- const outcome = await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters: kept, appKeys: keptKeys, output: null }, replay.fetch, redacted));
5105
+ const outcome = await settle(invokeSlot(plugin2, { slot, call: callName, args: keptArgs, parameters: kept, appKeys: keptKeys, output: null }, replay.fetch, redacted));
4793
5106
  const testCase = {
4794
5107
  slot,
4795
5108
  ...callName === void 0 ? {} : { call: callName },
4796
- args,
5109
+ args: keptArgs,
4797
5110
  ...redacted === null ? {} : { credentials: redacted },
4798
5111
  ...kept === void 0 ? {} : { parameters: kept },
4799
5112
  ...keptKeys === void 0 ? {} : { appKeys: keptKeys },
4800
5113
  exchanges,
4801
5114
  ...outcome
4802
5115
  };
5116
+ const left = leftoverValues(testCase, own);
5117
+ if (left.length > 0) throw new RecordRefused(`recorded case still holds ${left.length} credential value(s) after replacing them with fakes, nothing was recorded`);
4803
5118
  const findings = scanValue(testCase);
4804
5119
  if (findings.length > 0) throw new RecordRefused(`recorded case still holds credentials:
4805
5120
  ${findings.join("\n")}`);
4806
- await writeFile(out, `${JSON.stringify(testCase, null, 2)}
4807
- `);
5121
+ const text = `${JSON.stringify(testCase, null, 2)}
5122
+ `;
5123
+ if (holdsByteOrderMark(text)) throw new RecordRefused(`the plugin's arguments or output hold U+FEFF, nothing was recorded: ${BYTE_ORDER_MARK_IN_CASE}`);
5124
+ await writeFile(out, text);
4808
5125
  return testCase;
4809
5126
  }
4810
5127
  function withoutValues(value, secrets) {
4811
5128
  if (secrets.length === 0) return value;
4812
5129
  const walk = (item) => {
4813
- if (typeof item === "string") return secrets.reduce((text, secret) => text.split(secret).join(REDACTED), item);
5130
+ if (typeof item === "string") return secrets.reduce((text, secret) => text.split(secret).join(fakeSecret(secret)), item);
4814
5131
  if (Array.isArray(item)) return item.map(walk);
4815
5132
  if (item !== null && typeof item === "object") return Object.fromEntries(Object.entries(item).map(([key, entry]) => [key, walk(entry)]));
4816
5133
  return item;
4817
5134
  };
4818
5135
  return walk(value);
4819
5136
  }
5137
+ var LAYERS = 5;
5138
+ function encodings(text) {
5139
+ const out = [text];
5140
+ for (let layer = 0; layer < LAYERS; layer += 1) out.push(encodeURIComponent(out[out.length - 1]));
5141
+ return out;
5142
+ }
5143
+ function occurrences(own) {
5144
+ const fakeOf = /* @__PURE__ */ new Map();
5145
+ for (const { value, fake } of own) {
5146
+ const values = encodings(value);
5147
+ const fakes = encodings(fake);
5148
+ values.forEach((encoded, layer) => {
5149
+ if (!fakeOf.has(encoded)) fakeOf.set(encoded, fakes[layer]);
5150
+ });
5151
+ }
5152
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5153
+ const afterEscape = "(?<=%(?:25)*[0-9A-Fa-f]{2})";
5154
+ const alternatives = [...fakeOf.keys()].sort((a, b) => b.length - a.length).map((text) => /^\d+$/.test(text) ? `(?:(?<!\\d)|${afterEscape})${escape(text)}(?!\\d)` : `(?:(?<![A-Za-z0-9])|${afterEscape})${escape(text)}(?![A-Za-z0-9])`);
5155
+ return { pattern: new RegExp(alternatives.join("|"), "g"), fakeOf };
5156
+ }
5157
+ var asBytes = (text) => Buffer.from(text, "utf8").toString("latin1");
5158
+ function decodedLayers(bytes2) {
5159
+ const layers = [bytes2];
5160
+ for (let layer = 0; layer < LAYERS; layer += 1) {
5161
+ const last = layers[layers.length - 1];
5162
+ const next = last.replace(/%([0-9A-Fa-f]{2})/g, (_, hex2) => String.fromCharCode(parseInt(hex2, 16)));
5163
+ if (next === last) break;
5164
+ layers.push(next);
5165
+ }
5166
+ return layers;
5167
+ }
5168
+ function bytePattern(own) {
5169
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5170
+ return new RegExp([...new Set(own.map(({ value }) => asBytes(value)))].sort((a, b) => b.length - a.length).map((text) => /^\d+$/.test(text) ? `(?<!\\d)${escape(text)}(?!\\d)` : `(?<![A-Za-z0-9])${escape(text)}(?![A-Za-z0-9])`).join("|"), "g");
5171
+ }
5172
+ function withOwnValuesReplaced(value, own) {
5173
+ if (own.length === 0) return value;
5174
+ const { pattern, fakeOf } = occurrences(own);
5175
+ const walk = (item) => {
5176
+ if (typeof item === "string") return item.replace(pattern, (found) => fakeOf.get(found) ?? found);
5177
+ if (typeof item === "number") {
5178
+ const fake = fakeOf.get(String(item));
5179
+ return fake !== void 0 && /^\d+$/.test(fake) ? Number(fake) : item;
5180
+ }
5181
+ if (Array.isArray(item)) return item.map(walk);
5182
+ if (item !== null && typeof item === "object") {
5183
+ if (typeof item.$bytes === "string") return item;
5184
+ return Object.fromEntries(Object.entries(item).map(([key, entry]) => [walk(key), walk(entry)]));
5185
+ }
5186
+ return item;
5187
+ };
5188
+ return walk(value);
5189
+ }
5190
+ function leftoverValues(testCase, own) {
5191
+ const checked = own.filter(({ value }) => value.length >= 3 && !isRedacted(value));
5192
+ if (checked.length === 0) return [];
5193
+ const pattern = bytePattern(checked);
5194
+ const values = new Set(checked.map(({ value }) => value));
5195
+ const found = [];
5196
+ const inLayers = (text) => {
5197
+ const layers = decodedLayers(text).map((layer) => layer.match(pattern) ?? []);
5198
+ found.push(...layers.reduce((most, matches) => matches.length > most.length ? matches : most, []));
5199
+ };
5200
+ const walk = (item) => {
5201
+ if (typeof item === "string") return inLayers(asBytes(item));
5202
+ if (typeof item === "number") {
5203
+ if (values.has(String(item))) found.push(String(item));
5204
+ return;
5205
+ }
5206
+ if (Array.isArray(item)) return item.forEach(walk);
5207
+ if (item === null || typeof item !== "object") return;
5208
+ const bytes2 = item.$bytes;
5209
+ if (typeof bytes2 === "string") {
5210
+ return inLayers(Buffer.from(bytes2, "base64").toString("latin1"));
5211
+ }
5212
+ for (const [key, entry] of Object.entries(item)) {
5213
+ walk(key);
5214
+ walk(entry);
5215
+ }
5216
+ };
5217
+ walk(testCase);
5218
+ return found;
5219
+ }
4820
5220
  async function scanCommand(directories, log) {
4821
5221
  const { files: files2, findings } = await scanDirectories(directories);
4822
5222
  for (const finding of findings) log(`CREDENTIAL ${finding}`);
@@ -4833,41 +5233,7 @@ if (false) {
4833
5233
  }
4834
5234
  }
4835
5235
 
4836
- // plugins/trial-runner/sandbox.ts
4837
- import vm from "node:vm";
4838
- var UTF8_LABELS = /* @__PURE__ */ new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]);
4839
- var Utf8TextDecoder = class extends TextDecoder {
4840
- constructor(label = "utf-8", options) {
4841
- if (!UTF8_LABELS.has(String(label).trim().toLowerCase())) {
4842
- throw new RangeError(`TextDecoder only supports utf-8, not ${label}`);
4843
- }
4844
- super("utf-8", options);
4845
- }
4846
- };
4847
- async function loadPlugin(source, { identifier, allowCodeGeneration }) {
4848
- const context = vm.createContext({}, { codeGeneration: { strings: allowCodeGeneration, wasm: false } });
4849
- const remaining = vm.runInContext(`(() => {
4850
- const allowed = new Set(${JSON.stringify([...PLUGIN_GLOBALS])});
4851
- for (const name of Object.getOwnPropertyNames(globalThis)) if (!allowed.has(name)) delete globalThis[name];
4852
- return Object.getOwnPropertyNames(globalThis).filter((name) => !allowed.has(name));
4853
- })()`, context);
4854
- if (remaining.length > 0) throw new Error(`could not remove globals: ${remaining.join(", ")}`);
4855
- const global = vm.runInContext("globalThis", context);
4856
- const silent = () => {
4857
- };
4858
- const consoleObject = Object.freeze({ debug: silent, trace: silent, log: silent, info: silent, warn: silent, error: silent });
4859
- for (const [name, value] of [["TextEncoder", TextEncoder], ["TextDecoder", Utf8TextDecoder], ["console", consoleObject]]) {
4860
- Object.defineProperty(global, name, { value, writable: true, configurable: true });
4861
- }
4862
- const module = new vm.SourceTextModule(source, { context, identifier });
4863
- await module.link(() => {
4864
- throw new Error("plugins cannot import modules");
4865
- });
4866
- await module.evaluate();
4867
- return module.namespace;
4868
- }
4869
-
4870
- // plugins/packer/pack.ts
5236
+ // packer/pack.ts
4871
5237
  var TEMPLATES = fileURLToPath2(new URL("../templates/", import.meta.url));
4872
5238
  var SAMPLES = fileURLToPath2(new URL("../samples/src/", import.meta.url));
4873
5239
  var SAMPLE_PACKAGES = fileURLToPath2(new URL("../samples/dist/", import.meta.url));
@@ -4917,63 +5283,10 @@ async function dictionaries(directory) {
4917
5283
  if (problems.length > 0) throw new Error(`${directory}: ${problems.join("; ")}`);
4918
5284
  return result.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
4919
5285
  }
4920
- function inheritedFunctions(slot, functions) {
4921
- const inherited = /* @__PURE__ */ new Set();
4922
- for (let prototype = Object.getPrototypeOf(slot); prototype !== null; prototype = Object.getPrototypeOf(prototype)) {
4923
- for (const member of Object.getOwnPropertyNames(prototype)) {
4924
- if (functions.includes(member) && !Object.hasOwn(slot, member)) inherited.add(member);
4925
- }
4926
- }
4927
- return [...inherited];
4928
- }
4929
- function capabilitiesOf(namespace) {
4930
- const problems = [];
4931
- const found = /* @__PURE__ */ new Set();
4932
- for (const [name, value] of Object.entries(namespace)) {
4933
- const top = TOP_LEVEL_FUNCTIONS[name];
4934
- if (top !== void 0) {
4935
- if (typeof value === "function") found.add(top);
4936
- else problems.push(`${name} must be a function`);
4937
- continue;
4938
- }
4939
- const rule = SLOT_RULES[name];
4940
- if (rule === void 0) {
4941
- problems.push(`exports ${name}; plugins export only ${[...Object.keys(SLOT_RULES), ...Object.keys(TOP_LEVEL_FUNCTIONS)].join(", ")}`);
4942
- continue;
4943
- }
4944
- if (typeof value !== "object" || value === null) {
4945
- problems.push(`${name} must be an object of functions`);
4946
- continue;
4947
- }
4948
- const has = (member) => typeof slotMember(value, member) === "function";
4949
- for (const member of Object.getOwnPropertyNames(value)) {
4950
- if (!rule.functions.includes(member)) problems.push(`${name}.${member} is not in the contract (${rule.functions.join(", ")})`);
4951
- else if (!has(member)) problems.push(`${name}.${member} must be a function`);
4952
- }
4953
- for (const member of inheritedFunctions(value, rule.functions)) {
4954
- problems.push(`${name}.${member} is inherited; slot functions must be the object's own properties (an object literal, not a class instance)`);
4955
- }
4956
- for (const member of rule.required) if (!has(member)) problems.push(`${name} needs ${member}`);
4957
- for (const [first, second] of rule.pairs) {
4958
- if (has(first) !== has(second)) {
4959
- const [present, missing] = has(first) ? [first, second] : [second, first];
4960
- problems.push(`${name}.${present} needs ${name}.${missing}`);
4961
- }
4962
- }
4963
- const generated = Object.entries(rule.capabilities).filter(([, any]) => any.some(has)).map(([capability]) => capability);
4964
- generated.forEach((capability) => found.add(capability));
4965
- const all = Object.values(rule.capabilities).flat();
4966
- if (all.length > 0 && generated.length === 0) problems.push(`${name} needs one of ${all.join(", ")}`);
4967
- }
4968
- if (found.has("library") && found.has("resources")) {
4969
- problems.push("exports both library and resources; a source that lists all its content is scanned into the library, so it does not also answer find");
4970
- }
4971
- return { capabilities: Capability.values.filter((name) => found.has(name)), problems };
4972
- }
4973
5286
  function notYetUsedExports(namespace) {
4974
5287
  const unused = new Set(NOT_YET_USED);
4975
- const exported2 = Object.entries(namespace).flatMap(([name, value]) => TOP_LEVEL_FUNCTIONS[name] !== void 0 ? [name] : (SLOT_RULES[name]?.functions ?? []).filter((member) => typeof slotMember(value, member) === "function").map((member) => `${name}.${member}`));
4976
- return exported2.filter((name) => unused.has(name));
5288
+ const exported2 = Object.entries(namespace).flatMap(([name2, value]) => TOP_LEVEL_FUNCTIONS[name2] !== void 0 ? [name2] : (SLOT_RULES[name2]?.functions ?? []).filter((member) => typeof slotMember(value, member) === "function").map((member) => `${name2}.${member}`));
5289
+ return exported2.filter((name2) => unused.has(name2));
4977
5290
  }
4978
5291
  async function pack(directory, warn = () => {
4979
5292
  }) {
@@ -4996,12 +5309,12 @@ async function pack(directory, warn = () => {
4996
5309
  const { capabilities, problems } = capabilitiesOf(namespace);
4997
5310
  if (capabilities.length === 0 && problems.length === 0) problems.push("exports no capability; a plugin exports at least one slot or resolve");
4998
5311
  if (problems.length > 0) throw new Error(`${directory}: ${problems.join("; ")}`);
4999
- for (const name of notYetUsedExports(namespace)) warn(`WARN ${directory}: exports ${name}, which this version of the App does not call yet (App \u5C1A\u672A\u4F7F\u7528)`);
5312
+ for (const name2 of notYetUsedExports(namespace)) warn(`WARN ${directory}: exports ${name2}, which this version of the App does not call yet (App \u5C1A\u672A\u4F7F\u7528)`);
5000
5313
  const { default: metadata } = await import(pathToFileURL(join4(directory, "manifest.ts")).href);
5001
5314
  if (metadata.interfaceLevel > CONTRACT.interfaceLevel || metadata.contractRevision !== CONTRACT.revision) {
5002
5315
  throw new Error(`${directory}/manifest.ts targets interface level ${metadata.interfaceLevel} revision ${metadata.contractRevision}; the contract is level ${CONTRACT.interfaceLevel} revision ${CONTRACT.revision}`);
5003
5316
  }
5004
- const reserved = checkManifest(metadata);
5317
+ const reserved = checkManifest({ ...metadata, capabilities });
5005
5318
  if (reserved.length > 0) throw new Error(`${directory}/manifest.ts: ${reserved.join("; ")}`);
5006
5319
  const locales = await dictionaries(directory);
5007
5320
  if (locales.length > 0 && metadata.language === void 0) {
@@ -5033,7 +5346,7 @@ if (false) {
5033
5346
  }
5034
5347
  }
5035
5348
 
5036
- // plugins/package/cli.ts
5349
+ // package/cli.ts
5037
5350
  var here2 = dirname2(fileURLToPath3(import.meta.url));
5038
5351
  var ROOT = basename2(here2) === "dist" ? dirname2(here2) : here2;
5039
5352
  var PACKAGED = basename2(here2) === "dist";
@@ -5066,8 +5379,8 @@ async function bundle(directory, out, log) {
5066
5379
  function rewriteImports(source) {
5067
5380
  return source.replace(/from "(?:\.\.\/)+contract\/contract\.ts"/g, `from "${PACKAGE_NAME}"`);
5068
5381
  }
5069
- var SCAFFOLD_PACKAGE = (name, version) => ({
5070
- name,
5382
+ var SCAFFOLD_PACKAGE = (name2, version) => ({
5383
+ name: name2,
5071
5384
  private: true,
5072
5385
  type: "module",
5073
5386
  scripts: { check: `${PACKAGE_NAME} check`, bundle: `${PACKAGE_NAME} bundle`, trial: `${PACKAGE_NAME} trial` },
@@ -5090,7 +5403,7 @@ async function fallbackConfig(directory) {
5090
5403
  await writeFile3(config, JSON.stringify({ compilerOptions: COMPILER_OPTIONS, files: ["plugin.ts", "manifest.ts"].map((file) => join5(directory, file)) }));
5091
5404
  return config;
5092
5405
  }
5093
- async function newCommand(directory, { id, name, template = "apple-hls" }, log) {
5406
+ async function newCommand(directory, { id, name: name2, template = "apple-hls" }, log) {
5094
5407
  const target = resolve3(directory);
5095
5408
  if (existsSync(target) && (await readdir5(target)).length > 0) throw new UsageError(`${target} already exists and is not empty`);
5096
5409
  const source = join5(TEMPLATES2, template);
@@ -5101,7 +5414,7 @@ async function newCommand(directory, { id, name, template = "apple-hls" }, log)
5101
5414
  for (const file of ["plugin.ts", "manifest.ts"]) {
5102
5415
  await writeFile3(join5(target, file), rewriteImports(await readFile6(join5(target, file), "utf8")));
5103
5416
  }
5104
- const manifest = (await readFile6(join5(target, "manifest.ts"), "utf8")).replace(/id: "[^"]*"/, () => `id: ${JSON.stringify(pluginId)}`).replace(/sourceId: "[^"]*"/, () => `sourceId: ${JSON.stringify(slug)}`).replace(/name: "[^"]*"/, () => `name: ${JSON.stringify(name ?? basename2(target))}`).replace(/author: "[^"]*"/, () => `author: "<your name>"`).replace(/version: "[^"]*"/, () => `version: "0.1.0"`);
5417
+ const manifest = (await readFile6(join5(target, "manifest.ts"), "utf8")).replace(/id: "[^"]*"/, () => `id: ${JSON.stringify(pluginId)}`).replace(/sourceId: "[^"]*"/, () => `sourceId: ${JSON.stringify(slug)}`).replace(/name: "[^"]*"/, () => `name: ${JSON.stringify(name2 ?? basename2(target))}`).replace(/author: "[^"]*"/, () => `author: "<your name>"`).replace(/version: "[^"]*"/, () => `version: "0.1.0"`);
5105
5418
  await writeFile3(join5(target, "manifest.ts"), manifest);
5106
5419
  const { version } = JSON.parse(await readFile6(join5(ROOT, "package.json"), "utf8"));
5107
5420
  await writeFile3(join5(target, "package.json"), `${JSON.stringify(SCAFFOLD_PACKAGE(slug, version), null, 2)}