@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,747 @@
1
+ /**
2
+ * dsh-remote-control — Client half (web bundle).
3
+ *
4
+ * Rendered by the DSH web shell through `window.__ModuleLoader__.load`. Registers a
5
+ * "DSH Pocket" page in the Settings panel (`settings.section`) that shows:
6
+ * - the relay address (editable inline — no file editing required) and the
7
+ * pairing channel, plus the link status,
8
+ * - the pairing QR code (inline SVG produced by the Host half),
9
+ * - the actions: save the relay address, rotate the pairing key and
10
+ * hide / show the pairing.
11
+ *
12
+ * The phone pairing flow is unchanged: the QR still encodes the same
13
+ * `dshrc://pair?…` URI as before (contract §3.5) — only the entry point moved
14
+ * from the `/remote-pairing` command into this settings page (v1.1.x).
15
+ *
16
+ * Host communication goes through the `remoteControl` Remote namespace
17
+ * (`ctx.remote.remoteControl.getPairing() / setRelayUrl(url) / rotateSecret() /
18
+ * setHidden(hidden)`), published by the Host half in `index.js`.
19
+ */
20
+ /**
21
+ * This package's client-module id. It is both the `__ModuleLoader__.load` id and
22
+ * the HMR style owner (`data-plugin`) — client-modules keys style ownership off the
23
+ * registered id, so the two must stay the same string.
24
+ */
25
+ // COMBO-SAFETY (2026-10-24 production incident): the DSH web server concatenates
26
+ // every web client bundle into ONE combo <script> with NO scope wrapping
27
+ // (client-modules buildComboScript). Any top-level const/let/class would collide
28
+ // with the same name in another bundle (ours collided with token-stats' const
29
+ // CLIENT_BUNDLE_ID and killed the whole combo). The whole file therefore lives
30
+ // inside this IIFE: zero top-level declarations beyond the wrapper itself.
31
+ (() => {
32
+ const CLIENT_BUNDLE_ID = "@duke-dsh-plugins/dsh-remote-control";
33
+
34
+ window.__ModuleLoader__.load({
35
+ id: CLIENT_BUNDLE_ID,
36
+ factory: (require) => {
37
+ var module = { exports: {} };
38
+ var exports = module.exports;
39
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
40
+ const React = require("react");
41
+
42
+ // ==== BEGIN GENERATED ICON (scripts/sync-client-icon.mjs) ====
43
+ // Auto-generated from icon.svg — run `node scripts/sync-client-icon.mjs` after changing the icon.
44
+ const CLIENT_ICON_MASK_URI =
45
+ "data:image/svg+xml,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 viewBox%3D%228 8 32 34%22 fill%3D%22none%22%3E%0A %0A %0A %0A %3Cg fill%3D%22none%22 stroke%3D%22%23fff%22 stroke-width%3D%222.8%22 stroke-linecap%3D%22round%22 stroke-linejoin%3D%22round%22%3E%0A %3Cpath d%3D%22M10.5 12.5 Q24 15 37.5 12.5 L37.5 27 A10.5 10.5 0 0 1 27 37.5 H21 A10.5 10.5 0 0 1 10.5 27 Z%22%2F%3E%0A %3Cpath d%3D%22M14 16.6 Q24 18.4 34 16.6%22 stroke-opacity%3D%22.4%22 stroke-width%3D%221.3%22%2F%3E%0A %3C%2Fg%3E%0A %3Cg transform%3D%22translate(14.00%2C19.1) scale(0.8636)%22%3E%0A %3Cpath d%3D%22M22.9168 1.43018C22.6713 1.31018 22.5658 1.53918 22.4223 1.65519C22.3733 1.69269 22.3318 1.74169 22.2903 1.78669C21.9317 2.1697 21.5127 2.42121 20.9657 2.39121C20.1657 2.34621 19.4827 2.59771 18.8787 3.20973C18.7502 2.45521 18.3236 2.0047 17.6746 1.71569C17.3351 1.56568 16.9916 1.41518 16.7536 1.08867C16.5876 0.856163 16.5421 0.597155 16.4591 0.341647C16.4061 0.187643 16.3536 0.0301382 16.1761 0.00363739C15.9836 -0.0263635 15.9081 0.135141 15.8326 0.270145C15.5306 0.822162 15.4136 1.43018 15.4251 2.0462C15.4516 3.43174 16.0366 4.53527 17.1991 5.3203C17.3311 5.4103 17.3651 5.5003 17.3236 5.63181C17.2441 5.90231 17.1501 6.16482 17.0671 6.43533C17.0141 6.60784 16.9351 6.64584 16.7501 6.57033C16.1121 6.30383 15.5611 5.90931 15.074 5.4328C14.2475 4.63328 13.5 3.75075 12.568 3.05973C12.349 2.89822 12.13 2.74822 11.9034 2.60522C10.9524 1.68169 12.028 0.923165 12.277 0.833162C12.5375 0.739159 12.3675 0.41615 11.5259 0.42015C10.6844 0.42365 9.91439 0.705658 8.93286 1.08117C8.78935 1.13767 8.63835 1.17867 8.48384 1.21267C7.59332 1.04367 6.66829 1.00617 5.70226 1.11517C3.88321 1.31768 2.43016 2.1777 1.36213 3.64575C0.0790928 5.4103 -0.222916 7.41536 0.146595 9.50642C0.535106 11.7105 1.66014 13.535 3.38869 14.9616C5.18125 16.4406 7.24581 17.1657 9.60138 17.0266C11.0319 16.9441 12.6245 16.7526 14.421 15.2321C14.874 15.4576 15.3496 15.5476 16.1381 15.6151C16.7456 15.6716 17.3306 15.5851 17.7836 15.4911C18.4931 15.3411 18.4441 14.6841 18.1876 14.5636C16.1081 13.595 16.5646 13.9891 16.1496 13.67C17.2061 12.42 18.8202 10.1979 19.3182 7.17235C19.3672 6.83834 19.4297 6.36783 19.4222 6.09732C19.4182 5.93231 19.4562 5.86831 19.6447 5.84931C20.1657 5.78931 20.6712 5.64681 21.1357 5.3913C22.4833 4.65528 23.0268 3.44624 23.1548 1.9972C23.1738 1.77569 23.1508 1.54668 22.9168 1.43018ZM11.1749 14.4736C9.15936 12.889 8.18184 12.3675 7.77832 12.39C7.40081 12.4125 7.46881 12.8445 7.55182 13.126C7.63882 13.404 7.75182 13.5955 7.91033 13.8396C8.01983 14.0011 8.09533 14.2411 7.80083 14.4216C7.15181 14.8231 6.02327 14.2866 5.97027 14.2601C4.65673 13.4865 3.5587 12.4655 2.78467 11.069C2.03715 9.72493 1.60314 8.28289 1.53164 6.74384C1.51264 6.37233 1.62214 6.24082 1.99215 6.17332C2.47916 6.08332 2.98118 6.06432 3.46769 6.13582C5.52476 6.43633 7.27581 7.35586 8.74385 8.8129C9.58188 9.64243 10.2159 10.634 10.8689 11.6025C11.5634 12.631 12.3105 13.611 13.262 14.4146C13.598 14.6961 13.866 14.9101 14.1225 15.0681C13.349 15.1546 12.058 15.1731 11.1749 14.4746L11.1749 14.4736ZM12.141 8.25988C12.141 8.09488 12.273 7.96338 12.439 7.96338C12.4765 7.96338 12.5105 7.97088 12.541 7.98188C12.5825 7.99688 12.6205 8.01938 12.6505 8.05338C12.7035 8.10588 12.7335 8.18088 12.7335 8.25988C12.7335 8.42489 12.6015 8.55639 12.4355 8.55639C12.2695 8.55639 12.141 8.42489 12.141 8.25988ZM15.1415 9.79893C14.949 9.87793 14.7565 9.94544 14.5715 9.95294C14.2845 9.96794 13.9715 9.85143 13.8015 9.70893C13.5375 9.48742 13.3485 9.36342 13.2695 8.97691C13.2355 8.8119 13.2545 8.55639 13.2845 8.40989C13.3525 8.09438 13.277 7.89187 13.0545 7.70787C12.8735 7.55786 12.643 7.51636 12.39 7.51636C12.2955 7.51636 12.209 7.47486 12.1445 7.44136C12.039 7.38886 11.9519 7.25735 12.035 7.09585C12.0615 7.04335 12.19 6.91584 12.22 6.89334C12.5635 6.69784 12.9595 6.76184 13.326 6.90834C13.6655 7.04735 13.9225 7.30236 14.292 7.66287C14.6695 8.09838 14.7375 8.21838 14.9525 8.54539C15.1225 8.8009 15.277 9.06341 15.3831 9.36392C15.4471 9.55142 15.3641 9.70493 15.1415 9.79893Z%22 fill%3D%22%23fff%22%2F%3E%0A %3C%2Fg%3E%0A%3C%2Fsvg%3E";
46
+ // ==== END GENERATED ICON ====
47
+
48
+ // ---- CSS (package-owned, mirrors DSH design tokens) --------------------
49
+ const CSS = `
50
+ .rc-page{max-width:720px;width:100%;box-sizing:border-box;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:14px}
51
+ .rc-head{display:flex;align-items:center;gap:10px}
52
+ .rc-head-title{font-size:16px;font-weight:500;line-height:24px;margin:0;flex:1}
53
+ .rc-status{display:inline-flex;align-items:center;gap:6px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
54
+ .rc-dot{width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-label-tertiary);flex:none}
55
+ .rc-dot-online{background:var(--dsw-alias-state-success-primary)}
56
+ .rc-dot-offline{background:var(--dsw-alias-state-error-primary)}
57
+ .rc-card{background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:14px;display:flex;flex-direction:column;gap:10px}
58
+ .rc-card-title{font-size:14px;font-weight:500;line-height:20px;margin:0}
59
+ .rc-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
60
+ .rc-field{display:flex;flex-direction:column;gap:2px;min-width:0}
61
+ .rc-label{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary)}
62
+ .rc-value{font-size:13px;line-height:18px;color:var(--dsw-alias-label-primary);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;word-break:break-all}
63
+ .rc-input{box-sizing:border-box;height:30px;flex:1;min-width:240px;font:inherit;font-size:13px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);padding:0 10px}
64
+ .rc-input:focus{outline:none;border-color:var(--dsw-alias-border-l1)}
65
+ .rc-input::placeholder{color:var(--dsw-alias-label-tertiary)}
66
+ .rc-qr{display:flex;justify-content:center;padding:8px 0}
67
+ .rc-qr svg{width:220px;height:220px;max-width:100%;display:block;background:#fff;border-radius:10px;padding:8px}
68
+ .rc-qr-empty{color:var(--dsw-alias-label-secondary);font-size:13px;padding:24px 0;text-align:center}
69
+ .rc-note{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
70
+ .rc-actions{display:flex;gap:8px;flex-wrap:wrap}
71
+ .rc-btn{box-sizing:border-box;height:30px;font:inherit;cursor:pointer;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);padding:0 14px;font-size:13px;line-height:28px}
72
+ .rc-btn:hover{border-color:var(--dsw-alias-border-l1)}
73
+ .rc-btn:disabled{opacity:.5;cursor:default}
74
+ .rc-btn-primary{background:var(--dsw-alias-button-primary-fill);border-color:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}
75
+ .rc-btn-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover);border-color:var(--dsw-alias-button-primary-hover)}
76
+ .rc-hint{font-size:12px;line-height:18px;min-height:18px;color:var(--dsw-alias-label-secondary)}
77
+ .rc-hint-error{color:var(--dsw-alias-state-error-primary)}
78
+ .rc-hint-ok{color:var(--dsw-alias-state-success-primary)}
79
+ .rc-loading{display:flex;align-items:center;gap:10px;color:var(--dsw-alias-label-secondary);font-size:13px;padding:24px 0}
80
+ .rc-spinner{width:16px;height:16px;border-radius:50%;border:2px solid var(--dsw-alias-border-l1);border-top-color:var(--dsw-alias-brand-primary);animation:rc-spin .8s linear infinite;flex:none}
81
+ @keyframes rc-spin{to{transform:rotate(360deg)}}
82
+
83
+ /* Settings nav icon: DSH 0.1.x settings.section only projects id/order/label,
84
+ and the settings shell paints a generic gear for every external section
85
+ (client-ui-settings-general's navIcon()). registerSettingsNavIcon marks our
86
+ own nav row; hide the shell's gear and draw this package's whale glyph as a
87
+ currentColor mask so it follows the native nav hover/active colors.
88
+ 20px (2026-10-24 user feedback): the mask viewBox is cropped tight to the
89
+ whale+wave, so at 16px the glyph itself rendered only ~9px — too small next
90
+ to the section labels; 20px restores legibility. */
91
+ [data-dsh-remote-control-settings-nav]>svg:first-child{display:none}
92
+ [data-dsh-remote-control-settings-nav]::before{content:'';flex:none;width:20px;height:20px;background:currentColor;-webkit-mask:url("__ICON_MASK__") center/contain no-repeat;mask:url("__ICON_MASK__") center/contain no-repeat}
93
+ `;
94
+
95
+ // ---- Settings nav icon --------------------------------------------------
96
+ // DSH 0.1.x does not yet carry an icon through the settings.section
97
+ // registration contract: its shell projects only id/order/label and paints
98
+ // a generic gear for every external section. Mark only this plugin's
99
+ // localized nav row so the CSS above can replace the fallback gear; the
100
+ // disposer clears the marker for HMR / plugin disable.
101
+ const SETTINGS_LABEL = "DSH Pocket";
102
+ const SETTINGS_NAV_MARKER = "data-dsh-remote-control-settings-nav";
103
+
104
+ function registerSettingsNavIcon(label) {
105
+ let disposed = false;
106
+ const sync = function () {
107
+ if (disposed) return;
108
+ const currentLabel = String(label).trim();
109
+ const buttons = document.querySelectorAll('[role="dialog"] nav button');
110
+ for (let i = 0; i < buttons.length; i++) {
111
+ const button = buttons[i];
112
+ const text = button.textContent ? button.textContent.trim() : "";
113
+ if (currentLabel.length > 0 && text === currentLabel) {
114
+ button.setAttribute(SETTINGS_NAV_MARKER, "");
115
+ } else {
116
+ button.removeAttribute(SETTINGS_NAV_MARKER);
117
+ }
118
+ }
119
+ };
120
+ sync();
121
+ const observer = new MutationObserver(sync);
122
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
123
+ return function () {
124
+ disposed = true;
125
+ observer.disconnect();
126
+ const marked = document.querySelectorAll("[" + SETTINGS_NAV_MARKER + "]");
127
+ for (let i = 0; i < marked.length; i++) marked[i].removeAttribute(SETTINGS_NAV_MARKER);
128
+ };
129
+ }
130
+
131
+ // ---- Client Remote contribution ----------------------------------------
132
+ // The browser-side `remote.remoteControl` service only exists after this
133
+ // module mounts its namespace via ctx.remote.$mount(): dsh-api-remotes'
134
+ // client assembly mounts only the official namespaces, so a plugin must
135
+ // mount its own. Mirrors the invocations in typert.host.js (id,
136
+ // service/namespace/method). zod is not requirable in the browser module
137
+ // loader, so codecs use passthrough schemas — but they still need a
138
+ // create() factory: the client-side typert remote store REJECTS strict
139
+ // codecs without one ("has no create() factory" → dead Remote namespace).
140
+ const passthrough = () => ({ parse: (v) => v });
141
+ const createPassthrough = () => passthrough();
142
+ const CLIENT_REMOTE = {
143
+ package: "dsh-remote-control",
144
+ descriptors: [
145
+ {
146
+ id: "dsh-remote-control#remoteControl/getPairing",
147
+ service: "remoteControl",
148
+ namespace: "remoteControl",
149
+ method: "getPairing",
150
+ invocation: { kind: "direct" },
151
+ parameters: [],
152
+ result: {
153
+ mode: "strict",
154
+ typeSymbol: "dsh-remote-control#PairingResult",
155
+ schema: passthrough(),
156
+ create: createPassthrough,
157
+ },
158
+ },
159
+ {
160
+ id: "dsh-remote-control#remoteControl/rotateSecret",
161
+ service: "remoteControl",
162
+ namespace: "remoteControl",
163
+ method: "rotateSecret",
164
+ invocation: { kind: "direct" },
165
+ parameters: [],
166
+ result: {
167
+ mode: "strict",
168
+ typeSymbol: "dsh-remote-control#PairingResult",
169
+ schema: passthrough(),
170
+ create: createPassthrough,
171
+ },
172
+ },
173
+ {
174
+ id: "dsh-remote-control#remoteControl/setHidden",
175
+ service: "remoteControl",
176
+ namespace: "remoteControl",
177
+ method: "setHidden",
178
+ invocation: { kind: "direct" },
179
+ parameters: [
180
+ {
181
+ name: "hidden",
182
+ wire: "hidden",
183
+ source: "json",
184
+ codec: {
185
+ mode: "strict",
186
+ typeSymbol: "dsh-remote-control#remoteControl/setHidden:hidden",
187
+ schema: passthrough(),
188
+ create: createPassthrough,
189
+ },
190
+ },
191
+ ],
192
+ result: {
193
+ mode: "strict",
194
+ typeSymbol: "dsh-remote-control#PairingResult",
195
+ schema: passthrough(),
196
+ create: createPassthrough,
197
+ },
198
+ },
199
+ {
200
+ id: "dsh-remote-control#remoteControl/setRelayUrl",
201
+ service: "remoteControl",
202
+ namespace: "remoteControl",
203
+ method: "setRelayUrl",
204
+ invocation: { kind: "direct" },
205
+ parameters: [
206
+ {
207
+ name: "url",
208
+ wire: "url",
209
+ source: "json",
210
+ codec: {
211
+ mode: "strict",
212
+ typeSymbol: "dsh-remote-control#remoteControl/setRelayUrl:url",
213
+ schema: passthrough(),
214
+ create: createPassthrough,
215
+ },
216
+ },
217
+ ],
218
+ result: {
219
+ mode: "strict",
220
+ typeSymbol: "dsh-remote-control#PairingResult",
221
+ schema: passthrough(),
222
+ create: createPassthrough,
223
+ },
224
+ },
225
+ {
226
+ // v1.1.3:中继门口的鉴权令牌(对应中继的 RELAY_TOKEN)。
227
+ // 令牌进 transport hello(明文可见),因此设置页**不回显明文**——
228
+ // 只回 relayTokenSet(是否已设置),输入框留空即清除。
229
+ id: "dsh-remote-control#remoteControl/setRelayToken",
230
+ service: "remoteControl",
231
+ namespace: "remoteControl",
232
+ method: "setRelayToken",
233
+ invocation: { kind: "direct" },
234
+ parameters: [
235
+ {
236
+ name: "token",
237
+ wire: "token",
238
+ source: "json",
239
+ codec: {
240
+ mode: "strict",
241
+ typeSymbol: "dsh-remote-control#remoteControl/setRelayToken:token",
242
+ schema: passthrough(),
243
+ create: createPassthrough,
244
+ },
245
+ },
246
+ ],
247
+ result: {
248
+ mode: "strict",
249
+ typeSymbol: "dsh-remote-control#PairingResult",
250
+ schema: passthrough(),
251
+ create: createPassthrough,
252
+ },
253
+ },
254
+ ],
255
+ };
256
+
257
+ /**
258
+ * 双层信封解包(2026-10-24 修复二维码/频道/中继地址全空不显示):
259
+ * remote 网关返回 res.value = host 方法的 { ok, value|error } —— 网关在
260
+ * 宿主返回外又包了一层,必须拆两层(token-stats unwrapRemote 同款,其注释
261
+ * 原话「双层信封解包」)。此前单层拆包把内层信封整个当成了数据,页面
262
+ * relayUrl/channel/hidden/qrSvg 全部 undefined → 渲染全空;而宿主侧
263
+ * 真实生效(密钥轮换/隐藏/保存地址都落了盘),症状是「按钮有效但界面无反应」。
264
+ * 兼容:若某路径未包第二层(res.value 没有 ok 字段),按单层处理。
265
+ */
266
+ function unwrapRemote(res) {
267
+ if (!res || typeof res !== "object") {
268
+ return { ok: false, message: "宿主返回了无法识别的结果。" };
269
+ }
270
+ const inner =
271
+ res.value && typeof res.value === "object" && "ok" in res.value
272
+ ? res.value
273
+ : res;
274
+ if (inner.ok === true) return { ok: true, value: inner.value || {} };
275
+ const err = inner.error || {};
276
+ return { ok: false, message: err.message || err.code || "未知错误" };
277
+ }
278
+
279
+ /**
280
+ * 中继进程托管状态 → 一行中文(v1.1.1)。
281
+ * 宿主没给这个字段(旧插件)时显示「由外部管理」,不报错。
282
+ * @param {any} snap 宿主返回的 relayProcess 快照
283
+ * @returns {string}
284
+ */
285
+ function relayProcessText(snap) {
286
+ if (!snap || typeof snap !== "object") return "由外部管理";
287
+ if (snap.managed === true) {
288
+ if (snap.running === true) {
289
+ const pid = typeof snap.pid === "number" && snap.pid > 0 ? "(pid " + snap.pid + ")" : "";
290
+ return "插件托管 · 运行中" + pid;
291
+ }
292
+ return "插件托管 · 未运行(将自动重拉)";
293
+ }
294
+ // 端口上已有服务但不是插件起的 → 外部中继(插件不干预)
295
+ if (snap.external === true) {
296
+ const port = typeof snap.port === "number" && snap.port > 0 ? "(端口 " + snap.port + ")" : "";
297
+ return "外部中继 · 运行中" + port;
298
+ }
299
+ const detail = typeof snap.detail === "string" ? snap.detail : "";
300
+ if (detail) return detail;
301
+ return "由外部管理";
302
+ }
303
+
304
+ async function apply(ctx) {
305
+ try {
306
+ await applyInner(ctx);
307
+ } catch (e) {
308
+ // eslint-disable-next-line no-console
309
+ (typeof console !== "undefined" && console.error ? console.error : () => {})(
310
+ "[dsh-remote-control] client apply failed; plugin disabled for this session:",
311
+ e,
312
+ );
313
+ }
314
+ }
315
+
316
+ async function applyInner(ctx) {
317
+ // Mount the remoteControl namespace before anything touches it; the
318
+ // mount's lifetime is bound to this plugin's context by $mount itself. A
319
+ // mount failure downgrades the page to an error state instead of
320
+ // failing the whole bundle.
321
+ let remote = null;
322
+ try {
323
+ await ctx.remote.$mount(CLIENT_REMOTE);
324
+ remote = ctx.get("remote.remoteControl") || null;
325
+ } catch (e) {
326
+ // eslint-disable-next-line no-console
327
+ (typeof console !== "undefined" && console.warn ? console.warn : () => {})(
328
+ "[dsh-remote-control] remote.$mount failed; the settings page will show an error state:",
329
+ e,
330
+ );
331
+ }
332
+
333
+ let styleTag = null;
334
+ try {
335
+ styleTag = document.createElement("style");
336
+ styleTag.textContent = CSS.replace(/__ICON_MASK__/g, CLIENT_ICON_MASK_URI);
337
+ // dsh 0.2.0 client-modules runs `claimStyles(ownerId)` during
338
+ // materialization, which claims every *untagged* <style> in the
339
+ // document for the materializing package. `apply()` is async and appends
340
+ // this tag after that sweep, so without an explicit owner it would stay
341
+ // untagged and a later package could adopt it — and
342
+ // `removeOwnedStyles(thatId)` would then strip our stylesheet on its
343
+ // HMR invalidation. Claim it now.
344
+ styleTag.setAttribute("data-plugin", CLIENT_BUNDLE_ID);
345
+ document.head.appendChild(styleTag);
346
+ ctx.effect(() => () => styleTag && styleTag.remove());
347
+ } catch (e) {
348
+ /* cosmetic only */
349
+ }
350
+
351
+ // Mark our settings-nav row so the CSS above replaces the shell's
352
+ // fallback gear (no icon field exists in settings.section yet).
353
+ try {
354
+ ctx.effect(() => registerSettingsNavIcon(SETTINGS_LABEL));
355
+ } catch (e) {
356
+ /* cosmetic only */
357
+ }
358
+
359
+ function PairingPage() {
360
+ const [state, setState] = React.useState({ loading: true, value: null, error: "", hint: "", hintKind: "" });
361
+ const [busy, setBusy] = React.useState(false);
362
+ const [saving, setSaving] = React.useState(false);
363
+ // 中继地址输入框的草稿:null = 跟随宿主返回的值(没在编辑)
364
+ const [relayDraft, setRelayDraft] = React.useState(null);
365
+ // v1.1.3:中继令牌草稿(null = 跟随宿主值;宿主只回 relayTokenSet,不回明文)
366
+ const [tokenDraft, setTokenDraft] = React.useState(null);
367
+ // 宿主最近一次返回的中继地址:用来判断「宿主值真的变了」还是「只是轮询刷新」
368
+ const lastHostUrl = React.useRef(null);
369
+
370
+ const load = React.useCallback(async function () {
371
+ if (!remote) {
372
+ setState({ loading: false, value: null, error: "宿主 Remote 未就绪(remoteControl 未挂载)。", hint: "", hintKind: "" });
373
+ return;
374
+ }
375
+ try {
376
+ const res = unwrapRemote(await remote.getPairing());
377
+ if (!res.ok) {
378
+ setState({ loading: false, value: null, error: res.message, hint: "", hintKind: "" });
379
+ return;
380
+ }
381
+ const nextUrl = String((res.value && res.value.relayUrl) || "");
382
+ const hostChanged = lastHostUrl.current !== null && lastHostUrl.current !== nextUrl;
383
+ lastHostUrl.current = nextUrl;
384
+ // 宿主地址**真的变了**(保存成功/宿主侧改动)才让输入框回到跟随状态;
385
+ // 轮询刷新时地址没变 → 保留用户正在编辑的草稿。
386
+ if (hostChanged) setRelayDraft(null);
387
+ setState((s) => ({
388
+ loading: false,
389
+ value: res.value,
390
+ error: "",
391
+ // 轮询刷新**不要**覆盖用户的提示文案(保存后的绿色提示会被冲掉)
392
+ hint: hostChanged || s.hint === "" ? res.value.note || "" : s.hint,
393
+ hintKind: hostChanged || s.hint === "" ? "ok" : s.hintKind,
394
+ }));
395
+ } catch (e) {
396
+ setState((s) => ({
397
+ loading: false,
398
+ // 轮询失败不清空已有内容(可能是瞬时断连)
399
+ value: s.value || null,
400
+ error: s.value ? "" : String((e && e.message) || e),
401
+ hint: s.hint,
402
+ hintKind: s.hintKind,
403
+ }));
404
+ }
405
+ }, [remote]);
406
+
407
+ React.useEffect(() => {
408
+ load();
409
+ }, [load]);
410
+
411
+ // 轻量轮询:让「中继进程」状态保持实时(托管的中继崩了/被换掉时能看出来),
412
+ // 15s 一次,页面不可见时不做无用功。
413
+ React.useEffect(() => {
414
+ let timer = null;
415
+ const tick = () => {
416
+ if (typeof document !== "undefined" && document.hidden) return;
417
+ void load();
418
+ };
419
+ timer = setInterval(tick, 15_000);
420
+ return () => {
421
+ if (timer) clearInterval(timer);
422
+ };
423
+ }, [load]);
424
+
425
+ // 配对状态刷新后,输入框回到「跟随宿主值」——但**只在宿主地址真的变了**时
426
+ // (轮询刷新不能把用户正在编辑的草稿冲掉);判断已在上面的 load() 里完成。
427
+
428
+ // 保存中继地址:成功 → 刷新整页配对状态 + 绿色提示;失败 → 红色提示(宿主原文)
429
+ const saveRelay = React.useCallback(
430
+ async function (draft) {
431
+ if (!remote) return;
432
+ setSaving(true);
433
+ let note = "";
434
+ try {
435
+ const res = unwrapRemote(await remote.setRelayUrl(draft));
436
+ if (!res.ok) {
437
+ setState((s) => ({ ...s, hint: res.message, hintKind: "error" }));
438
+ return;
439
+ }
440
+ note = String(res.value?.note || "");
441
+ // 用新值先更新界面,再整页刷新(二维码/频道以宿主为准)
442
+ setState({
443
+ loading: false,
444
+ value: res.value,
445
+ error: "",
446
+ hint: "中继地址已更新" + (note ? ":" + note : ""),
447
+ hintKind: /回环|loopback/i.test(note) ? "error" : "ok",
448
+ });
449
+ await load();
450
+ setState((s) => ({
451
+ ...s,
452
+ hint: "中继地址已更新" + (note ? ":" + note : ""),
453
+ hintKind: /回环|loopback/i.test(note) ? "error" : "ok",
454
+ }));
455
+ } catch (e) {
456
+ setState((s) => ({ ...s, hint: String((e && e.message) || e), hintKind: "error" }));
457
+ } finally {
458
+ setSaving(false);
459
+ }
460
+ },
461
+ [remote, load],
462
+ );
463
+
464
+ // v1.1.3:保存中继令牌(留空 = 清除)。令牌进 transport hello → 必须重连链路。
465
+ const saveToken = React.useCallback(
466
+ async function (draft) {
467
+ if (!remote) return;
468
+ setSaving(true);
469
+ try {
470
+ const res = unwrapRemote(await remote.setRelayToken(draft));
471
+ if (!res.ok) {
472
+ setState((s) => ({ ...s, hint: res.message, hintKind: "error" }));
473
+ return;
474
+ }
475
+ setTokenDraft(null);
476
+ setState({
477
+ loading: false,
478
+ value: res.value,
479
+ error: "",
480
+ hint: String(draft || "").trim() === "" ? "中继令牌已清除" : "中继令牌已更新",
481
+ hintKind: "ok",
482
+ });
483
+ await load();
484
+ setState((s) => ({
485
+ ...s,
486
+ hint: String(draft || "").trim() === "" ? "中继令牌已清除" : "中继令牌已更新",
487
+ hintKind: "ok",
488
+ }));
489
+ } catch (e) {
490
+ setState((s) => ({ ...s, hint: String((e && e.message) || e), hintKind: "error" }));
491
+ } finally {
492
+ setSaving(false);
493
+ }
494
+ },
495
+ [remote, load],
496
+ );
497
+
498
+ const run = React.useCallback( async function (fn, okHint) {
499
+ if (!remote) return;
500
+ setBusy(true);
501
+ try {
502
+ const res = unwrapRemote(await fn());
503
+ if (!res.ok) {
504
+ setState((s) => ({ ...s, hint: res.message, hintKind: "error" }));
505
+ return;
506
+ }
507
+ setState({
508
+ loading: false,
509
+ value: res.value,
510
+ error: "",
511
+ hint: res.value.note || okHint,
512
+ hintKind: "ok",
513
+ });
514
+ } catch (e) {
515
+ setState((s) => ({ ...s, hint: String((e && e.message) || e), hintKind: "error" }));
516
+ } finally {
517
+ setBusy(false);
518
+ }
519
+ },
520
+ [remote],
521
+ );
522
+
523
+ if (state.loading) {
524
+ return React.createElement(
525
+ "div",
526
+ { className: "rc-page" },
527
+ React.createElement(
528
+ "div",
529
+ { className: "rc-loading" },
530
+ React.createElement("span", { className: "rc-spinner" }),
531
+ React.createElement("span", null, "正在读取配对信息…"),
532
+ ), );
533
+ }
534
+
535
+ const value = state.value || {};
536
+ const hidden = value.hidden === true;
537
+ const relayUrl = value.relayUrl || "";
538
+ const channel = value.channel || "";
539
+ const qrSvg = value.qrSvg || "";
540
+ const relayInput = relayDraft === null ? relayUrl : relayDraft;
541
+ // v1.1.3:令牌只显示「是否已设置」(不回显明文)
542
+ const tokenSet = value.relayTokenSet === true;
543
+ const tokenInput = tokenDraft === null ? "" : tokenDraft;
544
+ return React.createElement(
545
+ "div",
546
+ { className: "rc-page" },
547
+ // 头部:中继地址 + 连接状态
548
+ React.createElement(
549
+ "div",
550
+ { className: "rc-head" },
551
+ React.createElement("h2", { className: "rc-head-title" }, "DSH Pocket"),
552
+ React.createElement(
553
+ "span",
554
+ { className: "rc-status" },
555
+ React.createElement("span", {
556
+ className: "rc-dot " + (relayUrl ? "rc-dot-online" : "rc-dot-offline"),
557
+ }),
558
+ relayUrl ? "已配置中继" : "未配置中继",
559
+ ),
560
+ ),
561
+ state.error
562
+ ? React.createElement("div", { className: "rc-hint rc-hint-error" }, state.error)
563
+ : null,
564
+ // 配对信息
565
+ React.createElement(
566
+ "div",
567
+ { className: "rc-card" },
568
+ React.createElement("h3", { className: "rc-card-title" }, "配对信息"),
569
+ // 中继地址:可直接编辑保存(v1.1.x:不再要求用户改配置文件)
570
+ React.createElement(
571
+ "div",
572
+ { className: "rc-field" },
573
+ React.createElement("span", { className: "rc-label" }, "中继地址"),
574
+ React.createElement(
575
+ "div",
576
+ { className: "rc-row" },
577
+ React.createElement("input", {
578
+ type: "text",
579
+ className: "rc-input",
580
+ value: relayInput,
581
+ placeholder: "ws://192.168.x.x:8788",
582
+ spellCheck: false,
583
+ autoComplete: "off",
584
+ onChange: (e) => setRelayDraft(e && e.target ? e.target.value : ""),
585
+ }),
586
+ React.createElement(
587
+ "button",
588
+ {
589
+ type: "button",
590
+ className: "rc-btn",
591
+ disabled: saving || busy,
592
+ onClick: () => saveRelay(relayInput),
593
+ },
594
+ saving ? "保存中…" : "保存",
595
+ ),
596
+ ),
597
+ React.createElement(
598
+ "span",
599
+ { className: "rc-note" },
600
+ "留空即取消中继配置(插件停止连接)。手机需能访问该地址,填 localhost 手机连不上。",
601
+ ),
602
+ ),
603
+ // v1.1.3:中继门口的鉴权令牌(对应中继环境变量 RELAY_TOKEN)。
604
+ // 令牌会随配对二维码带给手机(契约 §3.5 的 t= 参数),也会放进
605
+ // transport hello——所以**不回显明文**,只显示「已设置 / 未设置」。
606
+ React.createElement(
607
+ "div",
608
+ { className: "rc-field" },
609
+ React.createElement("span", { className: "rc-label" }, "中继令牌"),
610
+ React.createElement(
611
+ "div",
612
+ { className: "rc-row" },
613
+ React.createElement("input", {
614
+ type: "password",
615
+ className: "rc-input",
616
+ value: tokenInput,
617
+ placeholder: tokenSet ? "已设置(留空并保存 = 清除)" : "可选:与中继的 RELAY_TOKEN 相同",
618
+ spellCheck: false,
619
+ autoComplete: "off",
620
+ onChange: (e) => setTokenDraft(e && e.target ? e.target.value : ""),
621
+ }),
622
+ React.createElement(
623
+ "button",
624
+ {
625
+ type: "button",
626
+ className: "rc-btn",
627
+ disabled: saving || busy,
628
+ onClick: () => saveToken(tokenInput),
629
+ },
630
+ saving ? "保存中…" : "保存",
631
+ ),
632
+ ),
633
+ React.createElement(
634
+ "span",
635
+ { className: "rc-note" },
636
+ tokenSet
637
+ ? "已设置:手机扫码时会自动带上。中继端需用同一个 RELAY_TOKEN 启动;留空保存即清除。"
638
+ : "未设置:中继未配置 RELAY_TOKEN 时不需要填。设置后手机扫码会自动带上。",
639
+ ),
640
+ ),
641
+ React.createElement(
642
+ "div",
643
+ { className: "rc-row" },
644
+ React.createElement(
645
+ "div",
646
+ { className: "rc-field" },
647
+ React.createElement("span", { className: "rc-label" }, "配对频道"),
648
+ React.createElement("span", { className: "rc-value" }, channel || "(无)"),
649
+ ),
650
+ ),
651
+ // v1.1.1:中继进程托管状态(让用户知道中继是谁在管、是否在跑)
652
+ React.createElement(
653
+ "div",
654
+ { className: "rc-row" },
655
+ React.createElement(
656
+ "div",
657
+ { className: "rc-field" },
658
+ React.createElement("span", { className: "rc-label" }, "中继进程"),
659
+ React.createElement(
660
+ "span",
661
+ { className: "rc-value" },
662
+ relayProcessText(value.relayProcess),
663
+ ),
664
+ ),
665
+ ),
666
+ ),
667
+ // 二维码卡片
668
+ React.createElement(
669
+ "div",
670
+ { className: "rc-card" },
671
+ React.createElement("h3", { className: "rc-card-title" }, "手机配对二维码"),
672
+ hidden
673
+ ? React.createElement(
674
+ "div",
675
+ { className: "rc-qr-empty" },
676
+ "配对已隐藏:手机端请使用此前扫码保存的配对信息。",
677
+ )
678
+ : qrSvg
679
+ ? React.createElement("div", {
680
+ className: "rc-qr",
681
+ dangerouslySetInnerHTML: { __html: qrSvg },
682
+ })
683
+ : React.createElement("div", { className: "rc-qr-empty" }, "填写中继地址并保存后,这里会显示手机配对二维码。"),
684
+ React.createElement(
685
+ "p",
686
+ { className: "rc-note" },
687
+ "二维码内含配对凭据,请勿截图分享;轮换密钥后旧码立即失效。",
688
+ ),
689
+ // 操作
690
+ React.createElement(
691
+ "div",
692
+ { className: "rc-actions" },
693
+ React.createElement(
694
+ "button",
695
+ {
696
+ type: "button",
697
+ className: "rc-btn rc-btn-primary",
698
+ disabled: busy,
699
+ onClick: () => run(() => remote.rotateSecret(), "密钥已轮换,旧二维码立即失效。"),
700
+ },
701
+ "轮换密钥",
702
+ ),
703
+ React.createElement(
704
+ "button",
705
+ {
706
+ type: "button",
707
+ className: "rc-btn",
708
+ disabled: busy,
709
+ onClick: () => run(() => remote.setHidden(!hidden), hidden ? "配对二维码已恢复显示。" : "配对二维码已隐藏。"),
710
+ },
711
+ hidden ? "显示配对" : "隐藏配对",
712
+ ),
713
+ ),
714
+ state.hint
715
+ ? React.createElement(
716
+ "div",
717
+ { className: "rc-hint" + (state.hintKind === "error" ? " rc-hint-error" : state.hintKind === "ok" ? " rc-hint-ok" : "") },
718
+ state.hint,
719
+ )
720
+ : null,
721
+ ),
722
+ );
723
+ }
724
+
725
+ // Settings entry: a full page under the sidebar Settings panel.
726
+ try {
727
+ ctx.slots.inject("settings.section", () =>
728
+ ctx.slots.register(
729
+ { name: "settings.section", id: "remote-control", order: 40, label: () => SETTINGS_LABEL },
730
+ PairingPage,
731
+ ),
732
+ );
733
+ } catch (e) {
734
+ // eslint-disable-next-line no-console
735
+ (typeof console !== "undefined" && console.warn ? console.warn : () => {})(
736
+ "[dsh-remote-control] settings.section registration failed:",
737
+ e,
738
+ );
739
+ }
740
+ }
741
+
742
+ exports.apply = apply;
743
+ exports.inject = ["slots", "remote"];
744
+ return module.exports;
745
+ },
746
+ });
747
+ })();