dsh-sub2api 0.4.1 → 0.4.3

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 (3) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/lib/client.js +209 -23
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.3
4
+
5
+ Interface polish, driven by an audit against the host's real design tokens.
6
+
7
+ - **Dark mode actually uses the warning colour.** The panel asked for
8
+ `--dsw-alias-state-warning-primary`; DSH defines `state-warn-primary`. The name
9
+ never matched, so the amber fell back to a light-mode value on dark surfaces.
10
+ - Keyboard focus is visible again: inline styles cannot express `:focus-visible`,
11
+ so one scoped stylesheet carries the ring, and buttons, rows and inputs gained
12
+ hover and pressed states that work on both themes.
13
+ - `prefers-reduced-motion` is respected.
14
+ - Model search matches the display name as well as the id, appears from five
15
+ models instead of nine, and reports how many matched.
16
+ - Progress bars are 6px tall with a real `progressbar` role and value.
17
+
18
+ ## 0.4.2
19
+
20
+ Recharge and key handling, which are the two places where a mistake costs
21
+ something real.
22
+
23
+ - **Order countdown and recovery.** The pay centre expires an unpaid order after
24
+ 30 minutes; the panel now counts it down, says so in plain words when it runs
25
+ out, and offers "重新打开支付页" so a closed tab is not a lost order.
26
+ - **"去支付" cannot be double-clicked** into two tabs, and a failed status poll
27
+ now says so instead of quietly stopping.
28
+ - **Rebuilding the key takes two clicks.** It revokes the key DSH is using right
29
+ now, so it asks once — with the button turning red — and offers 取消.
30
+ - **A revealed key puts itself back behind the mask** after eight seconds; the
31
+ clipboard already has it.
32
+ - Model refresh failures surface as a toast instead of an unhandled rejection.
33
+ - Which sections you left open is remembered per browser, and toasts announce
34
+ themselves to screen readers.
35
+
3
36
  ## 0.4.1
4
37
 
5
38
  - The panel shows the site as **Psapi** instead of Sub2API, matching the
package/lib/client.js CHANGED
@@ -159,10 +159,41 @@ window.__ModuleLoader__.load({
159
159
  base: "var(--dsw-alias-bg-base, #ffffff)",
160
160
  accent: "var(--dsw-alias-state-business-primary, #2563eb)",
161
161
  ok: "var(--dsw-alias-state-success-primary, #15803d)",
162
- warn: "var(--dsw-alias-state-warning-primary, #b45309)",
162
+ // DSH names it `warn`, not `warning`: the wrong name silently falls back
163
+ // to this light-mode amber and reads badly on a dark surface.
164
+ warn: "var(--dsw-alias-state-warn-primary, #b45309)",
163
165
  bad: "var(--dsw-alias-state-error-primary, #dc2626)",
164
166
  };
165
167
 
168
+ /**
169
+ * Focus rings for keyboard users.
170
+ *
171
+ * Everything here is inline styles, which cannot express `:focus-visible`,
172
+ * so a single scoped stylesheet carries the rule and the roots opt in with
173
+ * `data-sub2api`.
174
+ */
175
+ const FOCUS_CSS = [
176
+ "[data-sub2api] :focus-visible{outline:2px solid " + C.accent + ";outline-offset:2px;border-radius:8px}",
177
+ "[data-sub2api] input:focus-visible{outline-offset:1px}",
178
+ "[data-sub2api] button:focus:not(:focus-visible){outline:none}",
179
+ // A neutral overlay reads correctly on both light and dark surfaces,
180
+ // which `filter: brightness()` does not.
181
+ "[data-sub2api] [data-sub2api-btn]:not(:disabled):hover{box-shadow:inset 0 0 0 999px rgba(127,127,127,.09)}",
182
+ "[data-sub2api] [data-sub2api-btn]:not(:disabled):active{box-shadow:inset 0 0 0 999px rgba(127,127,127,.16)}",
183
+ "[data-sub2api] [data-sub2api-row]:hover{background:rgba(127,127,127,.055)}",
184
+ "@media (prefers-reduced-motion: reduce){[data-sub2api] *{transition:none!important;animation:none!important}}",
185
+ ].join("");
186
+
187
+ function installFocusStyles(doc) {
188
+ const id = "sub2api-focus";
189
+ if (!doc || typeof doc.getElementById !== "function") return;
190
+ if (doc.getElementById(id)) return;
191
+ const style = doc.createElement("style");
192
+ style.id = id;
193
+ style.textContent = FOCUS_CSS;
194
+ (doc.head || doc.documentElement).appendChild(style);
195
+ }
196
+
166
197
  const T = {
167
198
  card: {
168
199
  border: "0.5px solid " + C.line,
@@ -212,8 +243,14 @@ window.__ModuleLoader__.load({
212
243
  const variants = {
213
244
  primary: { border: "1px solid transparent", background: C.accent, color: "#fff" },
214
245
  ghost: { border: "0.5px solid transparent", background: "transparent", color: C.second },
246
+ // Destructive: rebuilding the key revokes the one in use.
247
+ danger: { border: "1px solid " + C.bad, background: "transparent", color: C.bad },
215
248
  };
216
- return h("button", { style: { ...base, ...(variants[variant] || {}), ...style }, ...rest }, children);
249
+ return h("button", {
250
+ "data-sub2api-btn": "",
251
+ style: { ...base, ...(variants[variant] || {}), ...style },
252
+ ...rest,
253
+ }, children);
217
254
  }
218
255
 
219
256
  function Card({ title, meta, children, id, aside }) {
@@ -339,8 +376,17 @@ window.__ModuleLoader__.load({
339
376
  h("div", { style: { display: "flex", justifyContent: "space-between", fontSize: 11.5, color: C.muted } },
340
377
  h("span", null, label),
341
378
  h("span", null, Math.round(p) + "%")),
342
- h("div", { style: { height: 4, borderRadius: 999, background: C.sunken, marginTop: 3, overflow: "hidden" } },
343
- h("div", { style: { width: p + "%", height: "100%", background: tone, borderRadius: 999 } })),
379
+ h("div", {
380
+ role: "progressbar",
381
+ "aria-label": label + "用量",
382
+ "aria-valuenow": Math.round(p),
383
+ "aria-valuemin": 0,
384
+ "aria-valuemax": 100,
385
+ style: { height: 6, borderRadius: 999, background: C.sunken, marginTop: 4, overflow: "hidden" },
386
+ },
387
+ h("div", {
388
+ style: { width: p + "%", height: "100%", background: tone, borderRadius: 999, transition: "width 240ms ease" },
389
+ })),
344
390
  );
345
391
  }
346
392
 
@@ -440,7 +486,11 @@ window.__ModuleLoader__.load({
440
486
 
441
487
  function Toasts({ items }) {
442
488
  if (items.length === 0) return null;
489
+ const worst = items.some((item) => item.tone === "error") ? "assertive" : "polite";
443
490
  return h("div", {
491
+ role: "status",
492
+ "aria-live": worst,
493
+ "aria-atomic": "false",
444
494
  style: {
445
495
  position: "sticky",
446
496
  top: 0,
@@ -472,6 +522,25 @@ window.__ModuleLoader__.load({
472
522
 
473
523
  // ----------------------------------------------------------- section
474
524
 
525
+ /**
526
+ * Which blocks the user left open, remembered per browser.
527
+ *
528
+ * The panel is reopened often and every block resets to the same default
529
+ * otherwise, which means scrolling past the ones you never look at.
530
+ */
531
+ const OPEN_KEY = "dsh-sub2api:sections";
532
+ const DEFAULT_OPEN = { models: true, recharge: false, account: false, key: false, diagnose: false };
533
+
534
+ function readOpenSections() {
535
+ try {
536
+ const raw = window.localStorage.getItem(OPEN_KEY);
537
+ const parsed = raw ? JSON.parse(raw) : null;
538
+ return parsed && typeof parsed === "object" ? { ...DEFAULT_OPEN, ...parsed } : DEFAULT_OPEN;
539
+ } catch {
540
+ return DEFAULT_OPEN;
541
+ }
542
+ }
543
+
475
544
  /** A titled block that can be folded away, so the page stays scannable. */
476
545
  function Collapsible({ title, meta, open, onToggle, children, id }) {
477
546
  return h("section", { id, style: T.card },
@@ -689,6 +758,10 @@ window.__ModuleLoader__.load({
689
758
 
690
759
  function KeyDetail({ state, pending, onCreate, onReveal }) {
691
760
  const [revealed, setRevealed] = useState("");
761
+ const [confirming, setConfirming] = useState(false);
762
+ const hideTimer = useRef(null);
763
+
764
+ useEffect(() => () => { if (hideTimer.current) clearTimeout(hideTimer.current); }, []);
692
765
 
693
766
  const copy = async () => {
694
767
  try {
@@ -696,11 +769,25 @@ window.__ModuleLoader__.load({
696
769
  setRevealed(text);
697
770
  if (text) await navigator.clipboard.writeText(text);
698
771
  toastStore.push("密钥已复制");
772
+ // Put the mask back: a plaintext key left on screen is a screenshot away
773
+ // from leaking, and the clipboard already has it.
774
+ if (hideTimer.current) clearTimeout(hideTimer.current);
775
+ hideTimer.current = setTimeout(() => setRevealed(""), 8000);
699
776
  } catch {
700
777
  toastStore.push("复制失败,请手动选择", "error");
701
778
  }
702
779
  };
703
780
 
781
+ // Rebuilding revokes the key DSH is using right now, so it takes two clicks.
782
+ const rebuild = async () => {
783
+ if (!confirming) {
784
+ setConfirming(true);
785
+ return;
786
+ }
787
+ setConfirming(false);
788
+ await onCreate();
789
+ };
790
+
704
791
  return h("div", null,
705
792
  h("div", { style: T.row },
706
793
  h("code", {
@@ -718,8 +805,22 @@ window.__ModuleLoader__.load({
718
805
  },
719
806
  }, revealed || state.keyMasked || "尚未创建"),
720
807
  h(Button, { onClick: copy, disabled: !state.hasKey }, "复制"),
721
- h(Button, { onClick: onCreate, disabled: pending.key },
722
- pending.key ? "处理中…" : state.hasKey ? "重建" : "创建"),
808
+ h(Button, {
809
+ onClick: rebuild,
810
+ disabled: pending.key,
811
+ variant: confirming && state.hasKey ? "danger" : "default",
812
+ title: confirming ? "再点一次将作废旧密钥" : undefined,
813
+ },
814
+ pending.key
815
+ ? "处理中…"
816
+ : !state.hasKey
817
+ ? "创建"
818
+ : confirming
819
+ ? "确认重建"
820
+ : "重建"),
821
+ confirming
822
+ ? h(Button, { variant: "ghost", onClick: () => setConfirming(false) }, "取消")
823
+ : null,
723
824
  ),
724
825
  h("div", { style: { ...T.hint, marginTop: 10 } },
725
826
  "密钥固定命名为 ", h("code", { style: T.mono }, state.keyName || "dsh"),
@@ -731,6 +832,16 @@ window.__ModuleLoader__.load({
731
832
 
732
833
  const PRESETS = [10, 20, 50, 100];
733
834
 
835
+ /** How long the pay centre keeps an unpaid order open. */
836
+ const ORDER_TTL_MS = 30 * 60 * 1000;
837
+
838
+ function mmss(ms) {
839
+ const total = Math.max(0, Math.floor(ms / 1000));
840
+ const m = Math.floor(total / 60);
841
+ const sec = total % 60;
842
+ return `${m}:${String(sec).padStart(2, "0")}`;
843
+ }
844
+
734
845
  function RechargeDetail({ state, pending, onRecharge, onPoll, onRefresh, onRedeem }) {
735
846
  const [amount, setAmount] = useState(20);
736
847
  const [custom, setCustom] = useState("");
@@ -738,14 +849,28 @@ window.__ModuleLoader__.load({
738
849
  const [status, setStatus] = useState(null);
739
850
  const [code, setCode] = useState("");
740
851
  const [showRedeem, setShowRedeem] = useState(false);
852
+ const [opening, setOpening] = useState(false);
853
+ const [now, setNow] = useState(() => Date.now());
741
854
  const timer = useRef(null);
742
855
 
743
856
  const multiplier = Number(state.rechargeMultiplier) > 0 ? Number(state.rechargeMultiplier) : 2;
744
857
  const value = custom !== "" ? Number(custom) : amount;
745
858
  const credit = Number.isFinite(value) ? value * multiplier : 0;
746
859
 
860
+ // An order expires in 30 minutes; showing the clock beats leaving the user
861
+ // staring at "等待付款…" that will never resolve.
747
862
  useEffect(() => {
748
863
  if (!order) return undefined;
864
+ const tick = setInterval(() => setNow(Date.now()), 1000);
865
+ return () => clearInterval(tick);
866
+ }, [order]);
867
+
868
+ const expiresAt = order && order.createdAt ? order.createdAt + ORDER_TTL_MS : null;
869
+ const leftMs = expiresAt === null ? null : expiresAt - now;
870
+ const expired = leftMs !== null && leftMs <= 0;
871
+
872
+ useEffect(() => {
873
+ if (!order || expired) return undefined;
749
874
  timer.current = setInterval(async () => {
750
875
  try {
751
876
  const result = await onPoll(order.orderNo);
@@ -758,28 +883,42 @@ window.__ModuleLoader__.load({
758
883
  await onRefresh();
759
884
  }
760
885
  }
761
- } catch {
886
+ } catch (e) {
762
887
  clearInterval(timer.current);
763
888
  timer.current = null;
889
+ toastStore.push(
890
+ "查询订单失败:" + (e instanceof Error ? e.message : String(e)) + ";可点「刷新」看余额",
891
+ "error",
892
+ );
764
893
  }
765
894
  }, 5000);
766
895
  return () => { if (timer.current) clearInterval(timer.current); };
767
- }, [order, onPoll, onRefresh]);
896
+ }, [order, onPoll, onRefresh, expired]);
768
897
 
769
898
  const start = async () => {
899
+ if (opening) return;
770
900
  const tab = window.open("", "_blank");
901
+ setOpening(true);
771
902
  try {
772
903
  const data = await onRecharge(value);
773
904
  const target = data.checkoutUrl || data.url;
774
905
  if (tab) tab.location.href = target;
775
906
  else window.open(target, "_blank", "noopener");
776
- if (data.orderNo) setOrder(data);
907
+ if (data.orderNo) setOrder({ ...data, createdAt: Date.now() });
777
908
  } catch (e) {
778
909
  if (tab) tab.close();
779
910
  toastStore.push(e instanceof Error ? e.message : String(e), "error");
911
+ } finally {
912
+ setOpening(false);
780
913
  }
781
914
  };
782
915
 
916
+ const reopen = () => {
917
+ const target = order && (order.checkoutUrl || order.url);
918
+ if (target) window.open(target, "_blank", "noopener");
919
+ else toastStore.push("没有可用的支付链接,请重新下单", "error");
920
+ };
921
+
783
922
  const redeem = async () => {
784
923
  try {
785
924
  const result = await onRedeem(code.trim());
@@ -822,16 +961,30 @@ window.__ModuleLoader__.load({
822
961
  h(Button, {
823
962
  variant: "primary",
824
963
  onClick: start,
825
- disabled: !state.loggedIn || !Number.isFinite(value) || value <= 0,
826
- }, "去支付"),
964
+ disabled: !state.loggedIn || !Number.isFinite(value) || value <= 0 || opening,
965
+ }, opening ? "正在下单…" : "去支付"),
827
966
  ),
828
967
  ),
829
968
  order
830
969
  ? h("div", { style: { marginTop: 12 } },
831
970
  h(Alert, {
832
- tone: status ? (status.tone === "done" ? "ok" : status.tone === "error" ? "error" : "info") : "info",
833
- title: "订单 " + order.orderNo,
834
- }, status ? status.text : "已打开支付页,等待付款…"))
971
+ tone: expired
972
+ ? "warn"
973
+ : status
974
+ ? status.tone === "done" ? "ok" : status.tone === "error" ? "error" : "info"
975
+ : "info",
976
+ title: "订单 " + order.orderNo + (leftMs !== null && !expired ? ` · 剩余 ${mmss(leftMs)}` : ""),
977
+ action: h(Button, {
978
+ size: "sm",
979
+ onClick: reopen,
980
+ style: { color: "inherit", borderColor: "currentColor", background: "transparent" },
981
+ }, expired ? "重新下单" : "重新打开支付页"),
982
+ },
983
+ expired
984
+ ? "订单已过 30 分钟有效期,没有支付的话已经作废,重新下单即可。"
985
+ : status
986
+ ? status.text
987
+ : "已打开支付页,等待付款…到账后余额会自动更新,这页不用守着。"))
835
988
  : null,
836
989
  h("div", { style: { marginTop: 12, display: "flex", gap: 8, alignItems: "center" } },
837
990
  h(Button, {
@@ -889,6 +1042,7 @@ window.__ModuleLoader__.load({
889
1042
  };
890
1043
 
891
1044
  return h("div", {
1045
+ "data-sub2api-row": "",
892
1046
  style: {
893
1047
  display: "flex",
894
1048
  alignItems: "center",
@@ -896,6 +1050,7 @@ window.__ModuleLoader__.load({
896
1050
  padding: "7px 12px",
897
1051
  borderTop: "0.5px solid " + C.line,
898
1052
  fontSize: 13,
1053
+ transition: "background 120ms ease",
899
1054
  },
900
1055
  },
901
1056
  h("input", {
@@ -960,7 +1115,10 @@ window.__ModuleLoader__.load({
960
1115
 
961
1116
  const filtered = useMemo(() => {
962
1117
  const q = query.trim().toLowerCase();
963
- return q === "" ? everything : everything.filter((m) => m.id.toLowerCase().includes(q));
1118
+ if (q === "") return everything;
1119
+ return everything.filter((m) =>
1120
+ m.id.toLowerCase().includes(q) || String(m.displayName ?? "").toLowerCase().includes(q),
1121
+ );
964
1122
  }, [everything, query]);
965
1123
 
966
1124
  const toggle = (id) => {
@@ -1013,21 +1171,35 @@ window.__ModuleLoader__.load({
1013
1171
  h("span", { style: { ...T.small, fontWeight: 500 } },
1014
1172
  showingAll && !dirty ? `全部 ${everything.length} 个` : `已选 ${checked.length} / ${everything.length}`),
1015
1173
  h("div", { style: { marginLeft: "auto", display: "flex", gap: 8 } },
1016
- h(Button, { size: "sm", onClick: onRefreshModels, disabled: pending.models },
1017
- pending.models ? "同步中…" : "刷新"),
1174
+ h(Button, {
1175
+ size: "sm",
1176
+ onClick: async () => {
1177
+ try {
1178
+ await onRefreshModels();
1179
+ } catch (e) {
1180
+ toastStore.push(e instanceof Error ? e.message : String(e), "error");
1181
+ }
1182
+ },
1183
+ disabled: pending.models,
1184
+ }, pending.models ? "同步中…" : "刷新"),
1018
1185
  h(Button, { size: "sm", onClick: () => setExpanded((v) => !v) },
1019
1186
  expanded ? "收起" : "管理"),
1020
1187
  ),
1021
1188
  ),
1022
1189
  expanded
1023
1190
  ? h("div", null,
1024
- everything.length > 8
1025
- ? h("div", { style: { marginBottom: 8 } },
1191
+ everything.length > 4
1192
+ ? h("div", { style: { marginBottom: 8, display: "flex", gap: 8, alignItems: "center" } },
1026
1193
  h(TextField, {
1027
- placeholder: "搜索模型",
1194
+ placeholder: "搜索模型 id 或名称",
1028
1195
  value: query,
1029
1196
  onChange: (e) => setQuery(e.target.value),
1030
- }))
1197
+ style: { flex: 1 },
1198
+ }),
1199
+ query.trim() === ""
1200
+ ? null
1201
+ : h("span", { style: { ...T.hint, whiteSpace: "nowrap" } },
1202
+ `${filtered.length} / ${everything.length}`))
1031
1203
  : null,
1032
1204
  h("div", {
1033
1205
  style: { maxHeight: 300, overflow: "auto", border: "0.5px solid " + C.line, borderRadius: 12 },
@@ -1115,7 +1287,15 @@ window.__ModuleLoader__.load({
1115
1287
  const [steps, setSteps] = useState(null);
1116
1288
  const [ready, setReady] = useState(undefined);
1117
1289
  const [announcements, setAnnouncements] = useState([]);
1118
- const [open, setOpen] = useState({ models: true, recharge: false, account: false, key: false, diagnose: false });
1290
+ const [open, setOpen] = useState(readOpenSections);
1291
+
1292
+ useEffect(() => {
1293
+ try {
1294
+ window.localStorage.setItem(OPEN_KEY, JSON.stringify(open));
1295
+ } catch {
1296
+ // Private mode or a full quota: folding still works, it just forgets.
1297
+ }
1298
+ }, [open]);
1119
1299
 
1120
1300
  const setBusy = (key, value) => setPending((prev) => ({ ...prev, [key]: value }));
1121
1301
  const run = useCallback(async (key, fn) => {
@@ -1310,7 +1490,10 @@ window.__ModuleLoader__.load({
1310
1490
  }
1311
1491
 
1312
1492
  function Section() {
1313
- return h(Boundary, null, h(SectionInner, null));
1493
+ useEffect(() => {
1494
+ installFocusStyles(typeof document === "undefined" ? undefined : document);
1495
+ }, []);
1496
+ return h("div", { "data-sub2api": "" }, h(Boundary, null, h(SectionInner, null)));
1314
1497
  }
1315
1498
 
1316
1499
  // ------------------------------------------------------------ badge
@@ -1355,6 +1538,7 @@ window.__ModuleLoader__.load({
1355
1538
 
1356
1539
  return h("button", {
1357
1540
  type: "button",
1541
+ "data-sub2api": "",
1358
1542
  title: detail,
1359
1543
  "aria-label": `Psapi ${known ? "余额 " + money(balance) : "余额未知"},点击${low ? "去充值" : "刷新"}`,
1360
1544
  onClick,
@@ -1467,6 +1651,8 @@ window.__ModuleLoader__.load({
1467
1651
  exports.inject = inject;
1468
1652
  exports.Section = Section;
1469
1653
  exports.BalanceBadge = BalanceBadge;
1654
+ // Exposed for the load test: pure read/write of the remembered layout.
1655
+ exports.__sections = { readOpenSections, DEFAULT_OPEN, OPEN_KEY };
1470
1656
  return module.exports;
1471
1657
  },
1472
1658
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sub2api",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Psapi (sub.pscly.cc) provider for DeepSeek Harness: zero-friction signup, auto-provisioned API key, upstream model sync, balance and recharge",
5
5
  "type": "module",
6
6
  "license": "GPL-3.0-only",