@leonhoy/dsh-localstate-sync 0.0.0-stage → 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.
package/client.js ADDED
@@ -0,0 +1,969 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@leonhoy/dsh-localstate-sync',
3
+ factory(require) {
4
+ var React = require('react')
5
+ var META_KEY = '__dsh.localstate.meta.v1'
6
+ var ROUTE = 'api/localstate.v1'
7
+ var FLUSH_DELAY = 400
8
+ var MAX_RETRY_DELAY = 15000
9
+ var GUARD = '__DSH_LOCALSTATE_CAPTURE__'
10
+
11
+ function routeUrl() {
12
+ return new URL(ROUTE, document.baseURI).href
13
+ }
14
+
15
+ function defaultAllow() {
16
+ return { prefixes: ['dsh.'], exact: [], exclude: [] }
17
+ }
18
+
19
+ function allowed(state, key) {
20
+ if (typeof key !== 'string' || key === '' || key.length > 512) return false
21
+ var allow = state.allow
22
+ if (allow.exclude.indexOf(key) !== -1) return false
23
+ if (allow.exact.indexOf(key) !== -1) return true
24
+ for (var index = 0; index < allow.prefixes.length; index += 1) {
25
+ if (allow.prefixes[index] !== '' && key.indexOf(allow.prefixes[index]) === 0) return true
26
+ }
27
+ return false
28
+ }
29
+
30
+ function readMeta() {
31
+ var parsed
32
+ try {
33
+ parsed = JSON.parse(localStorage.getItem(META_KEY) || 'null')
34
+ } catch (error) {
35
+ parsed = null
36
+ }
37
+ if (!parsed || typeof parsed !== 'object' || !parsed.at || typeof parsed.at !== 'object') return { seq: 0, at: {} }
38
+ var at = {}
39
+ Object.keys(parsed.at).forEach(function (key) {
40
+ if (typeof parsed.at[key] === 'number') at[key] = parsed.at[key]
41
+ })
42
+ return { seq: typeof parsed.seq === 'number' ? parsed.seq : 0, at: at }
43
+ }
44
+
45
+ function writeMeta(meta) {
46
+ try {
47
+ localStorage.setItem(META_KEY, JSON.stringify(meta))
48
+ } catch (error) {
49
+ // The metadata write is best effort; a failure costs one redundant restore.
50
+ }
51
+ }
52
+
53
+ function applySnapshot(state, data) {
54
+ if (!data || data.v !== 1 || !Array.isArray(data.keys)) return 0
55
+ var meta = readMeta()
56
+ var applied = 0
57
+ for (var index = 0; index < data.keys.length; index += 1) {
58
+ var row = data.keys[index]
59
+ if (!Array.isArray(row) || row.length < 3) continue
60
+ var key = row[0]
61
+ var value = row[1]
62
+ var revision = row[2]
63
+ if (typeof key !== 'string' || typeof revision !== 'number') continue
64
+ if (!allowed(state, key)) continue
65
+ var known = typeof meta.at[key] === 'number' ? meta.at[key] : 0
66
+ if (revision <= known) continue
67
+ try {
68
+ if (value === null) localStorage.removeItem(key)
69
+ else if (typeof value === 'string') localStorage.setItem(key, value)
70
+ else continue
71
+ } catch (error) {
72
+ continue
73
+ }
74
+ meta.at[key] = revision
75
+ applied += 1
76
+ }
77
+ if (typeof data.seq === 'number' && data.seq > meta.seq) meta.seq = data.seq
78
+ state.known = meta.at
79
+ writeMeta(meta)
80
+ return applied
81
+ }
82
+
83
+ function applyConfig(state, config) {
84
+ if (!config || typeof config !== 'object') return
85
+ var next = defaultAllow()
86
+ if (Array.isArray(config.prefixes)) next.prefixes = config.prefixes.filter(function (item) { return typeof item === 'string' })
87
+ if (Array.isArray(config.exact)) next.exact = config.exact.filter(function (item) { return typeof item === 'string' })
88
+ if (Array.isArray(config.exclude)) next.exclude = config.exclude.filter(function (item) { return typeof item === 'string' })
89
+ state.allow = next
90
+ if (typeof config.capture === 'boolean') state.capture = config.capture
91
+ }
92
+
93
+ var BUNDLE_NAME = '@leonhoy/dsh-localstate-sync'
94
+ var CONFIG_EVENT = 'dsh-localstate:config-changed'
95
+ var CONFIG_ROUTE = 'api/localstate.config.v1'
96
+ var FORM_CSS = [
97
+ '.lssync-form{display:flex;flex-direction:column;gap:16px;max-width:720px;font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary,#1f2328)}',
98
+ '.lssync-lead{margin:0;color:var(--dsw-alias-label-secondary,#5b636e)}',
99
+ '.lssync-field{display:flex;flex-direction:column;gap:6px;padding-bottom:14px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.18))}',
100
+ '.lssync-field:last-of-type{border-bottom:none}',
101
+ '.lssync-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
102
+ '.lssync-name{font-weight:600}',
103
+ '.lssync-code{font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px;color:var(--dsw-alias-label-secondary,#5b636e)}',
104
+ '.lssync-badge{font-size:11px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3));color:var(--dsw-alias-label-secondary,#5b636e)}',
105
+ '.lssync-badge[data-on="true"]{border-color:var(--dsw-alias-brand-primary,#1f8a70);color:var(--dsw-alias-brand-primary,#1f8a70)}',
106
+ '.lssync-help{margin:0;color:var(--dsw-alias-label-secondary,#5b636e)}',
107
+ '.lssync-input,.lssync-area{font:inherit;color:inherit;background:var(--dsw-alias-bg-layer-1,transparent);border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.3));border-radius:6px;padding:6px 8px;width:100%;box-sizing:border-box}',
108
+ '.lssync-area{resize:vertical;min-height:84px;font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px}',
109
+ '.lssync-toggle{display:flex;align-items:center;gap:8px}',
110
+ '.lssync-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}',
111
+ '.lssync-button{font:inherit;padding:6px 16px;border-radius:6px;border:1px solid transparent;cursor:pointer;background:var(--dsw-alias-brand-primary,#1f8a70);color:#fff}',
112
+ '.lssync-button[disabled]{opacity:.55;cursor:default}',
113
+ '.lssync-note{color:var(--dsw-alias-label-secondary,#5b636e)}',
114
+ '.lssync-note[data-state="error"]{color:var(--dsw-alias-state-error,#c62828)}',
115
+ '.lssync-warn{margin:0;color:var(--dsw-alias-state-warn,#a15c00)}',
116
+ ].join('')
117
+
118
+ var FORM_TEXT = {
119
+ en: {
120
+ lead: 'Values are written into the profile patch layer (cordis.patch.yml). Saving restarts this bundle, so capture pauses for a moment.',
121
+ save: 'Save',
122
+ saving: 'Saving…',
123
+ saved: 'Saved.',
124
+ restarting: 'Saved — applying the new configuration.',
125
+ pending: 'Nothing changed yet.',
126
+ unavailable: 'The configuration endpoint is unreachable. Reload the page and try again.',
127
+ set: 'override',
128
+ inherit: 'default',
129
+ listHint: 'One entry per line.',
130
+ invalid: 'This field needs a number.',
131
+ rejected: 'Rejected',
132
+ stateFile: 'State file',
133
+ clashOne: '1 key kept its local value; the synced copy moved on. Reload to take the newer value:',
134
+ clashMany: '{n} keys kept their local values; the synced copy moved on. Reload to take the newer values:',
135
+ },
136
+ zh: {
137
+ lead: '值写入 profile 补丁层(cordis.patch.yml)。保存会重启本插件,采集会中断片刻。',
138
+ save: '保存',
139
+ saving: '保存中…',
140
+ saved: '已保存。',
141
+ restarting: '已保存,正在应用新配置。',
142
+ pending: '还没有改动。',
143
+ unavailable: '配置接口不可达,请刷新页面后重试。',
144
+ set: '已覆盖',
145
+ inherit: '默认',
146
+ listHint: '每行一个条目。',
147
+ invalid: '这个字段需要数字。',
148
+ rejected: '被拒绝',
149
+ stateFile: '状态文件',
150
+ clashOne: '有 1 个键保留了本地值:云端已更新,刷新页面后才会取用云端值:',
151
+ clashMany: '有 {n} 个键保留了本地值:云端已更新,刷新页面后才会取用云端值:',
152
+ },
153
+ }
154
+
155
+ var FORM_LABELS_ZH = {
156
+ enabled: '启用整个插件',
157
+ capture: '采集浏览器对 localStorage 的写入',
158
+ injectSnapshot: '页面启动前注入快照',
159
+ file: '状态文件(相对 DSH home)',
160
+ includePrefixes: '采集的键前缀',
161
+ includeExact: '额外采集的完整键',
162
+ excludeExact: '永不采集的完整键',
163
+ maxBytes: '快照总字节上限',
164
+ maxKeys: '保留的键数量上限',
165
+ injectMaxBytes: '注入头部的字节上限',
166
+ language: '提示与设置界面的语言',
167
+ }
168
+
169
+ var NOTICE_HOST_ID = '__dsh_localstate_toasts'
170
+
171
+ var NOTICE_TEXT = {
172
+ en: {
173
+ pushFailed: 'Push failed: the synced copy already moved to revision {n}. Reload to take the newer value.',
174
+ pulled: 'Restored {n} keys from the synced copy (the local values were older).',
175
+ reload: 'Reload',
176
+ dismiss: 'Dismiss',
177
+ },
178
+ zh: {
179
+ pushFailed: '推送失败:云端已更新到 revision {n},请刷新后重试。',
180
+ pulled: '已更新到云端版本({n} 项本地值更旧)。',
181
+ reload: '刷新',
182
+ dismiss: '关闭',
183
+ },
184
+ }
185
+
186
+ function noticeText(language) {
187
+ return NOTICE_TEXT[String(language || 'en').indexOf('zh') === 0 ? 'zh' : 'en']
188
+ }
189
+
190
+ function fillSlot(text, value) {
191
+ return String(text).split('{n}').join(String(value))
192
+ }
193
+
194
+ function publishNotice(entry) {
195
+ try {
196
+ var list = globalThis.__DSH_LOCALSTATE_NOTICES__
197
+ if (!Array.isArray(list)) list = []
198
+ list.push(entry)
199
+ while (list.length > 20) list.shift()
200
+ globalThis.__DSH_LOCALSTATE_NOTICES__ = list
201
+ } catch (error) {
202
+ // Diagnostics only.
203
+ }
204
+ }
205
+
206
+ function toastContainer() {
207
+ var host = document.getElementById(NOTICE_HOST_ID)
208
+ if (host) return host
209
+ host = document.createElement('div')
210
+ host.id = NOTICE_HOST_ID
211
+ host.setAttribute('data-plugin', 'localstate-sync')
212
+ host.style.cssText =
213
+ 'position:fixed;right:16px;bottom:16px;z-index:2147483000;display:flex;flex-direction:column;gap:8px;max-width:420px;pointer-events:none;font-family:inherit'
214
+ document.body.appendChild(host)
215
+ return host
216
+ }
217
+
218
+ /**
219
+ * A synced value moved on: the write was refused, so say so instead of
220
+ * silently keeping the local copy. The only way back to a shared value is a
221
+ * reload, which is exactly what the notice offers.
222
+ */
223
+ function notice(kind, text, options) {
224
+ var settings = options || {}
225
+ publishNotice({ kind: kind, text: text, at: Date.now(), key: typeof settings.key === 'string' ? settings.key : null })
226
+ try {
227
+ if (typeof document === 'undefined' || !document.body) return
228
+ var host = toastContainer()
229
+ var card = document.createElement('div')
230
+ card.className = 'lssync-toast lssync-toast-' + kind
231
+ card.setAttribute('role', kind === 'error' ? 'alert' : 'status')
232
+ card.style.cssText =
233
+ 'pointer-events:auto;display:flex;align-items:flex-start;gap:10px;padding:10px 12px;border-radius:10px;font-size:13px;line-height:1.45;' +
234
+ 'background:var(--dsw-alias-bg-overlay,#ffffff);color:var(--dsw-alias-label-primary,#111111);' +
235
+ 'border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.12));border-left:3px solid ' +
236
+ (kind === 'error' ? 'var(--dsw-alias-state-error,#b3261e)' : 'var(--dsw-alias-brand-primary,#1f8a70)') +
237
+ ';box-shadow:0 6px 24px rgba(0,0,0,.16)'
238
+ var label = document.createElement('span')
239
+ label.style.flex = '1'
240
+ label.textContent = text
241
+ card.appendChild(label)
242
+ function button(text, action) {
243
+ var element = document.createElement('button')
244
+ element.type = 'button'
245
+ element.textContent = text
246
+ element.style.cssText =
247
+ 'appearance:none;border:0;background:transparent;cursor:pointer;padding:0 2px;font:inherit;color:var(--dsw-alias-brand-primary,#1f8a70)'
248
+ element.addEventListener('click', action)
249
+ card.appendChild(element)
250
+ return element
251
+ }
252
+ function dismiss() {
253
+ try {
254
+ card.remove()
255
+ } catch (error) {
256
+ // The card may already be gone.
257
+ }
258
+ }
259
+ if (kind === 'error') {
260
+ button(settings.actionLabel || 'Reload', function () {
261
+ try {
262
+ location.reload()
263
+ } catch (error) {
264
+ // Nothing else to do if reload is blocked.
265
+ }
266
+ })
267
+ }
268
+ button(settings.dismissLabel || '×', dismiss)
269
+ host.appendChild(card)
270
+ if (kind !== 'error') setTimeout(dismiss, 8000)
271
+ } catch (error) {
272
+ // Notices are cosmetic; capture must keep working without them.
273
+ }
274
+ }
275
+ function configUrl() {
276
+ try {
277
+ return new URL(CONFIG_ROUTE, document.baseURI).href
278
+ } catch (error) {
279
+ return CONFIG_ROUTE
280
+ }
281
+ }
282
+
283
+ function formText(language) {
284
+ return FORM_TEXT[String(language || 'en').indexOf('zh') === 0 ? 'zh' : 'en']
285
+ }
286
+
287
+ // The configured language wins ('zh' / 'en'); 'auto' follows the browser, then the DSH
288
+ // locale, then the document language. The DSH UI itself may be English while the person
289
+ // reading the notices is not, so the browser is asked before the app.
290
+ var bootLanguage = 'auto'
291
+
292
+ function configuredLanguage() {
293
+ try {
294
+ var snapshot = globalThis.__DSH_LOCALSTATE__
295
+ if (snapshot && snapshot.config && typeof snapshot.config.language === 'string') return snapshot.config.language
296
+ } catch (error) {
297
+ // No injected snapshot: fall back to whatever refresh() learned.
298
+ }
299
+ return bootLanguage
300
+ }
301
+
302
+ function browserLanguage() {
303
+ try {
304
+ var list = navigator.languages !== undefined && navigator.languages.length > 0 ? navigator.languages : [navigator.language]
305
+ for (var index = 0; index < list.length; index += 1) {
306
+ if (typeof list[index] === 'string' && list[index] !== '') return list[index]
307
+ }
308
+ } catch (error) {
309
+ // No navigator: fall through.
310
+ }
311
+ return undefined
312
+ }
313
+
314
+ function detectLanguage(ctx, props) {
315
+ if (props && typeof props.language === 'string' && props.language !== '') return props.language
316
+ var chosen = configuredLanguage()
317
+ if (chosen === 'zh' || chosen === 'en') return chosen
318
+ var browser = browserLanguage()
319
+ if (browser !== undefined) return browser
320
+ try {
321
+ var snapshot = ctx.locale && typeof ctx.locale.getSnapshot === 'function' ? ctx.locale.getSnapshot() : undefined
322
+ if (snapshot && typeof snapshot.active === 'string') return snapshot.active
323
+ } catch (error) {
324
+ // Falls through to the document language.
325
+ }
326
+ var declared = document.documentElement.getAttribute('lang')
327
+ return typeof declared === 'string' && declared !== '' ? declared : 'en'
328
+ }
329
+
330
+ function createConfigForm(React, ctx) {
331
+ var h = React.createElement
332
+
333
+ function valueOf(draft, values, name) {
334
+ return Object.prototype.hasOwnProperty.call(draft, name) ? draft[name] : values[name]
335
+ }
336
+
337
+ function asText(value) {
338
+ if (Array.isArray(value)) return value.join('\n')
339
+ if (value === undefined || value === null) return ''
340
+ return String(value)
341
+ }
342
+
343
+ function asList(text) {
344
+ return String(text)
345
+ .split(/[\n,]/)
346
+ .map(function (item) {
347
+ return item.trim()
348
+ })
349
+ .filter(function (item) {
350
+ return item !== ''
351
+ })
352
+ }
353
+
354
+ return function LocalStateConfigForm(props) {
355
+ var language = detectLanguage(ctx, props)
356
+ var text = formText(language)
357
+ var labels = String(language).indexOf('zh') === 0 ? FORM_LABELS_ZH : undefined
358
+
359
+ var infoState = React.useState({ status: 'loading' })
360
+ var info = infoState[0]
361
+ var setInfo = infoState[1]
362
+ var draftState = React.useState({})
363
+ var draft = draftState[0]
364
+ var setDraft = draftState[1]
365
+ var noteState = React.useState({ text: '', error: false })
366
+ var note = noteState[0]
367
+ var setNote = noteState[1]
368
+ var busyState = React.useState(false)
369
+ var busy = busyState[0]
370
+ var setBusy = busyState[1]
371
+ var aliveState = React.useState(function () {
372
+ return { value: true }
373
+ })
374
+ var alive = aliveState[0]
375
+
376
+ function say(message, error) {
377
+ setNote({ text: message, error: error === true })
378
+ }
379
+
380
+ function applyBody(body) {
381
+ if (!body || body.ok !== true || !Array.isArray(body.fields)) return false
382
+ setInfo({ status: 'ready', body: body })
383
+ return true
384
+ }
385
+
386
+ function load() {
387
+ fetch(configUrl(), { method: 'GET', credentials: 'same-origin', cache: 'no-store' })
388
+ .then(function (response) {
389
+ return response.ok ? response.json() : Promise.reject(new Error('HTTP ' + response.status))
390
+ })
391
+ .then(function (body) {
392
+ if (alive.value) applyBody(body)
393
+ })
394
+ .catch(function (error) {
395
+ if (!alive.value) return
396
+ setInfo({ status: 'unavailable', message: String((error && error.message) || error) })
397
+ })
398
+ }
399
+
400
+ React.useEffect(function () {
401
+ alive.value = true
402
+ if (globalThis.__DSH_LOCALSTATE_CONFIG_CSS__ !== true) {
403
+ var style = document.createElement('style')
404
+ style.setAttribute('data-plugin-css', '@leonhoy/dsh-localstate-sync/client-form')
405
+ style.textContent = FORM_CSS
406
+ document.head.appendChild(style)
407
+ globalThis.__DSH_LOCALSTATE_CONFIG_CSS__ = true
408
+ }
409
+ load()
410
+ return function () {
411
+ alive.value = false
412
+ }
413
+ }, [])
414
+
415
+ function edit(name, value) {
416
+ setDraft(function (current) {
417
+ var next = {}
418
+ Object.keys(current).forEach(function (key) {
419
+ next[key] = current[key]
420
+ })
421
+ next[name] = value
422
+ return next
423
+ })
424
+ say('', false)
425
+ }
426
+
427
+ function changes(values) {
428
+ var out = {}
429
+ Object.keys(draft).forEach(function (name) {
430
+ if (JSON.stringify(draft[name]) !== JSON.stringify(values[name])) out[name] = draft[name]
431
+ })
432
+ return out
433
+ }
434
+
435
+ function settle(expected, attempt) {
436
+ fetch(configUrl(), { method: 'GET', credentials: 'same-origin', cache: 'no-store' })
437
+ .then(function (response) {
438
+ return response.ok ? response.json() : undefined
439
+ })
440
+ .then(function (body) {
441
+ if (!alive.value) return
442
+ var values = body && body.values ? body.values : {}
443
+ var pending = Object.keys(expected).some(function (name) {
444
+ return JSON.stringify(values[name]) !== JSON.stringify(expected[name])
445
+ })
446
+ if (body !== undefined) applyBody(body)
447
+ if (!pending) say(text.saved, false)
448
+ else if (attempt < 8) setTimeout(function () { settle(expected, attempt + 1) }, 600)
449
+ })
450
+ .catch(function () {
451
+ if (alive.value && attempt < 8) setTimeout(function () { settle(expected, attempt + 1) }, 600)
452
+ })
453
+ }
454
+
455
+ function save() {
456
+ if (info.status !== 'ready' || busy) return
457
+ var values = info.body.values || {}
458
+ var payload = changes(values)
459
+ if (Object.keys(payload).length === 0) {
460
+ say(text.pending, false)
461
+ return
462
+ }
463
+ var fields = {}
464
+ info.body.fields.forEach(function (field) {
465
+ fields[field.name] = field
466
+ })
467
+ var invalid = Object.keys(payload).some(function (name) {
468
+ var field = fields[name]
469
+ return field !== undefined && field.kind === 'number' && (typeof payload[name] !== 'number' || isNaN(payload[name]))
470
+ })
471
+ if (invalid) {
472
+ say(text.invalid, true)
473
+ return
474
+ }
475
+ setBusy(true)
476
+ say(text.saving, false)
477
+ fetch(configUrl(), {
478
+ method: 'POST',
479
+ credentials: 'same-origin',
480
+ cache: 'no-store',
481
+ headers: { 'content-type': 'application/json' },
482
+ body: JSON.stringify({ config: payload }),
483
+ })
484
+ .then(function (response) {
485
+ return response
486
+ .json()
487
+ .catch(function () {
488
+ return undefined
489
+ })
490
+ .then(function (body) {
491
+ return { ok: response.ok, status: response.status, body: body }
492
+ })
493
+ })
494
+ .then(function (result) {
495
+ if (!alive.value) return
496
+ setBusy(false)
497
+ if (!result.ok) {
498
+ var reason = result.body && result.body.reason ? result.body.reason : 'HTTP ' + result.status
499
+ var detail = result.body && result.body.message ? ': ' + result.body.message : ''
500
+ say(text.rejected + ' (' + reason + detail + ')', true)
501
+ return
502
+ }
503
+ setDraft({})
504
+ say(text.restarting, false)
505
+ var merged = {}
506
+ Object.keys(values).forEach(function (name) {
507
+ merged[name] = values[name]
508
+ })
509
+ Object.keys(payload).forEach(function (name) {
510
+ merged[name] = payload[name]
511
+ })
512
+ settle(merged, 0)
513
+ try {
514
+ window.dispatchEvent(new Event(CONFIG_EVENT))
515
+ } catch (error) {
516
+ // Capture keeps working with the previous allowlist.
517
+ }
518
+ })
519
+ .catch(function (error) {
520
+ if (!alive.value) return
521
+ setBusy(false)
522
+ say(String((error && error.message) || error), true)
523
+ })
524
+ }
525
+
526
+ if (props && props.view === 'summary') return null
527
+
528
+ if (info.status === 'loading') {
529
+ return h('p', { className: 'lssync-lead' }, '…')
530
+ }
531
+ if (info.status === 'unavailable') {
532
+ return h('p', { className: 'lssync-lead' }, text.unavailable + (info.message ? ' (' + info.message + ')' : ''))
533
+ }
534
+
535
+ var body = info.body
536
+ var values = body.values || {}
537
+ var explicit = Array.isArray(body.explicit) ? body.explicit : []
538
+
539
+ var rows = body.fields.map(function (field) {
540
+ var value = valueOf(draft, values, field.name)
541
+ var label = labels && labels[field.name] ? labels[field.name] : field.description
542
+ var control
543
+ if (field.kind === 'boolean') {
544
+ control = h(
545
+ 'label',
546
+ { className: 'lssync-toggle' },
547
+ h('input', {
548
+ type: 'checkbox',
549
+ checked: value === true,
550
+ onChange: function (event) {
551
+ edit(field.name, event.target.checked)
552
+ },
553
+ }),
554
+ h('span', { className: 'lssync-help' }, field.name),
555
+ )
556
+ } else if (field.kind === 'number') {
557
+ control = h('input', {
558
+ className: 'lssync-input',
559
+ type: 'number',
560
+ value: value === undefined || value === null ? '' : String(value),
561
+ min: field.min,
562
+ max: field.max,
563
+ step: 1,
564
+ onChange: function (event) {
565
+ var next = event.target.value === '' ? undefined : Number(event.target.value)
566
+ edit(field.name, next)
567
+ },
568
+ })
569
+ } else if (field.kind === 'array') {
570
+ control = h('textarea', {
571
+ className: 'lssync-area',
572
+ spellCheck: false,
573
+ rows: 4,
574
+ value: asText(value),
575
+ onChange: function (event) {
576
+ edit(field.name, asList(event.target.value))
577
+ },
578
+ })
579
+ } else if (field.kind === 'union' && Array.isArray(field.options) && field.options.length > 0) {
580
+ control = h(
581
+ 'select',
582
+ {
583
+ className: 'lssync-input',
584
+ value: value === undefined || value === null ? '' : String(value),
585
+ onChange: function (event) {
586
+ edit(field.name, event.target.value)
587
+ },
588
+ },
589
+ field.options.map(function (option) {
590
+ return h('option', { key: option, value: option }, option)
591
+ }),
592
+ )
593
+ } else {
594
+ control = h('input', {
595
+ className: 'lssync-input',
596
+ type: 'text',
597
+ spellCheck: false,
598
+ value: asText(value),
599
+ onChange: function (event) {
600
+ edit(field.name, event.target.value)
601
+ },
602
+ })
603
+ }
604
+ var hints = []
605
+ if (field.kind === 'array') hints.push(text.listHint)
606
+ if (field.default !== undefined && field.kind !== 'array') hints.push('default: ' + String(field.default))
607
+ if (field.kind === 'number' && field.min !== undefined) hints.push('min ' + field.min + (field.max !== undefined ? ', max ' + field.max : ''))
608
+ return h(
609
+ 'div',
610
+ { className: 'lssync-field', key: field.name },
611
+ h(
612
+ 'div',
613
+ { className: 'lssync-head' },
614
+ h('span', { className: 'lssync-name' }, label),
615
+ h('span', { className: 'lssync-code' }, field.name),
616
+ h('span', { className: 'lssync-badge', 'data-on': explicit.indexOf(field.name) === -1 ? 'false' : 'true' }, explicit.indexOf(field.name) === -1 ? text.inherit : text.set),
617
+ ),
618
+ control,
619
+ hints.length === 0 ? null : h('p', { className: 'lssync-help' }, hints.join(' · ')),
620
+ )
621
+ })
622
+
623
+ var clashKeys = []
624
+ try {
625
+ var reported = globalThis.__DSH_LOCALSTATE_CONFLICTS__
626
+ if (reported !== null && typeof reported === 'object') clashKeys = Object.keys(reported)
627
+ } catch (error) {
628
+ clashKeys = []
629
+ }
630
+ var clashRow =
631
+ clashKeys.length === 0
632
+ ? null
633
+ : h(
634
+ 'p',
635
+ { className: 'lssync-warn' },
636
+ (clashKeys.length === 1 ? text.clashOne : text.clashMany.replace('{n}', String(clashKeys.length))) + ' ' + clashKeys.join(', '),
637
+ )
638
+
639
+ return h(
640
+ 'div',
641
+ { className: 'lssync-form' },
642
+ h('p', { className: 'lssync-lead' }, text.lead),
643
+ h('p', { className: 'lssync-help' }, text.stateFile + ': ' + String(body.filePath || '')),
644
+ clashRow,
645
+ rows,
646
+ h(
647
+ 'div',
648
+ { className: 'lssync-actions' },
649
+ h('button', { className: 'lssync-button', type: 'button', disabled: busy || body.writable !== true, onClick: save }, busy ? text.saving : text.save),
650
+ note.text === '' ? null : h('span', { className: 'lssync-note', 'data-state': note.error ? 'error' : 'ok' }, note.text),
651
+ ),
652
+ )
653
+ }
654
+ }
655
+
656
+ function service(ctx, name) {
657
+ try {
658
+ var value = ctx.get(name)
659
+ if (value !== undefined && value !== null) return value
660
+ } catch (error) {
661
+ // Not registered yet; falls through to the guarded property read.
662
+ }
663
+ try {
664
+ return ctx[name]
665
+ } catch (error) {
666
+ return undefined
667
+ }
668
+ }
669
+
670
+ function registerConfigCell(ctx, React) {
671
+ var slots = service(ctx, 'slots')
672
+ if (slots === undefined || slots === null || typeof slots.register !== 'function') return
673
+ var Component = createConfigForm(React, ctx)
674
+ slots.inject('plugins.bundle.config', function () {
675
+ return slots.register(
676
+ {
677
+ name: 'plugins.bundle.config',
678
+ key: BUNDLE_NAME,
679
+ inject: function () {
680
+ return {}
681
+ },
682
+ },
683
+ Component,
684
+ )
685
+ })
686
+ }
687
+
688
+ return {
689
+ apply: function (ctx) {
690
+ if (typeof window === 'undefined') return
691
+ // `ctx.slots` is a guarded service read: touching an undeclared service
692
+ // throws, so ask the context for it explicitly and fall back quietly.
693
+ registerConfigCell(ctx, React)
694
+ if (typeof localStorage === 'undefined') return
695
+ if (location.protocol === 'file:') return
696
+ if (window[GUARD] === true) return
697
+
698
+ var state = {
699
+ allow: defaultAllow(),
700
+ capture: true,
701
+ known: {},
702
+ /** Revisions the local values were built on, sent as the write guard. */
703
+ base: {},
704
+ /** Keys that already lost one conflict and keep their local value. */
705
+ conflicts: {},
706
+ /** Keys resent once with a refreshed base, to avoid a ping-pong loop. */
707
+ retried: {},
708
+ pending: new Map(),
709
+ timer: undefined,
710
+ retryTimer: undefined,
711
+ retry: 0,
712
+ inflight: false,
713
+ }
714
+
715
+ var injected = globalThis.__DSH_LOCALSTATE__
716
+ if (injected && Array.isArray(injected.prefixes)) state.allow.prefixes = injected.prefixes
717
+ state.known = readMeta().at
718
+ state.base = { ...state.known }
719
+ applySnapshot(state, injected)
720
+
721
+ // The head seeder runs before the app boots and reports how many keys it
722
+ // replaced with a newer synced copy. Nothing to say when it replaced none.
723
+ var restored = 0
724
+ try {
725
+ if (typeof globalThis.__DSH_LOCALSTATE_APPLIED__ === 'number') restored = globalThis.__DSH_LOCALSTATE_APPLIED__
726
+ } catch (error) {
727
+ restored = 0
728
+ }
729
+ if (restored > 0) {
730
+ var bootText = noticeText(detectLanguage(ctx, {}))
731
+ notice('info', fillSlot(bootText.pulled, restored), { dismissLabel: bootText.dismiss })
732
+ }
733
+
734
+ function schedule() {
735
+ if (state.timer !== undefined) return
736
+ state.timer = setTimeout(function () {
737
+ state.timer = undefined
738
+ flush(false)
739
+ }, FLUSH_DELAY)
740
+ }
741
+
742
+ function requeue(sending) {
743
+ for (var index = 0; index < sending.length; index += 1) {
744
+ var key = sending[index][0]
745
+ if (!state.pending.has(key)) state.pending.set(key, sending[index][1])
746
+ }
747
+ }
748
+
749
+ function scheduleRetry() {
750
+ if (state.retryTimer !== undefined) return
751
+ var delay = Math.min(MAX_RETRY_DELAY, 1000 * Math.pow(2, state.retry))
752
+ state.retry = Math.min(state.retry + 1, 4)
753
+ state.retryTimer = setTimeout(function () {
754
+ state.retryTimer = undefined
755
+ flush(false)
756
+ }, delay)
757
+ }
758
+
759
+ function publishConflicts() {
760
+ try {
761
+ globalThis.__DSH_LOCALSTATE_CONFLICTS__ = state.conflicts
762
+ } catch (error) {
763
+ // Diagnostics only.
764
+ }
765
+ }
766
+
767
+ function adopt(sending, body) {
768
+ if (!body || body.ok !== true || !Array.isArray(body.accepted)) {
769
+ requeue(sending)
770
+ scheduleRetry()
771
+ return
772
+ }
773
+ var meta = readMeta()
774
+ for (var index = 0; index < body.accepted.length; index += 1) {
775
+ var pair = body.accepted[index]
776
+ if (!Array.isArray(pair)) continue
777
+ if (typeof pair[0] === 'string' && typeof pair[1] === 'number') {
778
+ meta.at[pair[0]] = pair[1]
779
+ state.base[pair[0]] = pair[1]
780
+ }
781
+ }
782
+ if (typeof body.seq === 'number') meta.seq = body.seq
783
+ if (Array.isArray(body.conflicts)) adoptConflicts(sending, body.conflicts, meta)
784
+ state.known = meta.at
785
+ writeMeta(meta)
786
+ state.retry = 0
787
+ }
788
+
789
+ /**
790
+ * A key whose base revision moved on was not applied. Resend it once with
791
+ * the fresh base; if it conflicts again the write FAILED: keep the local
792
+ * value visible, leave the base revision untouched (so a reload really
793
+ * does pull the newer synced copy), and tell the user to reload.
794
+ */
795
+ function adoptConflicts(sending, conflicts, meta) {
796
+ var local = {}
797
+ var changed = false
798
+ for (var index = 0; index < sending.length; index += 1) local[sending[index][0]] = sending[index][1]
799
+ for (var cursor = 0; cursor < conflicts.length; cursor += 1) {
800
+ var row = conflicts[cursor]
801
+ if (row === null || typeof row !== 'object' || typeof row.key !== 'string') continue
802
+ if (!Object.hasOwn(local, row.key)) continue
803
+ if (state.retried[row.key] !== true) {
804
+ state.retried[row.key] = true
805
+ if (typeof row.current === 'number') state.base[row.key] = row.current
806
+ if (!state.pending.has(row.key)) state.pending.set(row.key, local[row.key])
807
+ changed = true
808
+ continue
809
+ }
810
+ state.conflicts[row.key] = { local: local[row.key], remote: row.value, at: row.current }
811
+ var failure = noticeText(detectLanguage(ctx, {}))
812
+ notice('error', fillSlot(failure.pushFailed, row.current), {
813
+ key: row.key,
814
+ actionLabel: failure.reload,
815
+ dismissLabel: failure.dismiss,
816
+ })
817
+ }
818
+ publishConflicts()
819
+ if (changed) schedule()
820
+ }
821
+
822
+ function flush(useBeacon) {
823
+ if (state.capture === false || state.inflight || state.pending.size === 0) return
824
+ var changes = {}
825
+ var base = {}
826
+ var hasBase = false
827
+ var sending = []
828
+ state.pending.forEach(function (value, key) {
829
+ changes[key] = value
830
+ sending.push([key, value])
831
+ if (typeof state.base[key] === 'number') {
832
+ base[key] = state.base[key]
833
+ hasBase = true
834
+ }
835
+ })
836
+ var payload = JSON.stringify(hasBase ? { changes: changes, base: base } : { changes: changes })
837
+ state.pending.clear()
838
+ if (useBeacon && typeof navigator.sendBeacon === 'function' && payload.length < 60000) {
839
+ try {
840
+ navigator.sendBeacon(routeUrl(), new Blob([payload], { type: 'application/json' }))
841
+ } catch (error) {
842
+ requeue(sending)
843
+ }
844
+ return
845
+ }
846
+ state.inflight = true
847
+ fetch(routeUrl(), {
848
+ method: 'POST',
849
+ credentials: 'same-origin',
850
+ cache: 'no-store',
851
+ headers: { 'content-type': 'application/json' },
852
+ body: payload,
853
+ keepalive: payload.length < 60000,
854
+ })
855
+ .then(function (response) {
856
+ return response.ok ? response.json() : undefined
857
+ })
858
+ .then(function (body) {
859
+ state.inflight = false
860
+ adopt(sending, body)
861
+ })
862
+ .catch(function () {
863
+ state.inflight = false
864
+ requeue(sending)
865
+ scheduleRetry()
866
+ })
867
+ }
868
+
869
+ function refresh() {
870
+ fetch(routeUrl(), { method: 'GET', credentials: 'same-origin', cache: 'no-store' })
871
+ .then(function (response) {
872
+ return response.ok ? response.json() : undefined
873
+ })
874
+ .then(function (body) {
875
+ if (body === undefined) return
876
+ applyConfig(state, body.config)
877
+ if (typeof body.config === 'object' && body.config !== null && typeof body.config.language === 'string') {
878
+ bootLanguage = body.config.language
879
+ }
880
+ applySnapshot(state, body)
881
+ })
882
+ .catch(function () {
883
+ // The injected snapshot already covered this boot.
884
+ })
885
+ }
886
+
887
+ ctx.effect(function () {
888
+ window[GUARD] = true
889
+ var proto = window.Storage && window.Storage.prototype
890
+ var originals = proto === undefined ? undefined : {
891
+ setItem: proto.setItem,
892
+ removeItem: proto.removeItem,
893
+ clear: proto.clear,
894
+ }
895
+
896
+ function observe(key, value) {
897
+ if (!allowed(state, key)) return
898
+ state.pending.set(key, value)
899
+ schedule()
900
+ }
901
+
902
+ if (originals !== undefined) {
903
+ proto.setItem = function (key, value) {
904
+ var result = originals.setItem.call(this, key, value)
905
+ try {
906
+ if (this === window.localStorage) observe(String(key), String(value))
907
+ } catch (error) {
908
+ // Capture never changes the outcome of the original call.
909
+ }
910
+ return result
911
+ }
912
+ proto.removeItem = function (key) {
913
+ var result = originals.removeItem.call(this, key)
914
+ try {
915
+ if (this === window.localStorage) observe(String(key), null)
916
+ } catch (error) {
917
+ // See above.
918
+ }
919
+ return result
920
+ }
921
+ proto.clear = function () {
922
+ var result = originals.clear.call(this)
923
+ try {
924
+ if (this === window.localStorage) {
925
+ var known = Object.keys(readMeta().at).concat(Object.keys(state.known))
926
+ for (var index = 0; index < known.length; index += 1) observe(known[index], null)
927
+ }
928
+ } catch (error) {
929
+ // See above.
930
+ }
931
+ return result
932
+ }
933
+ }
934
+
935
+ var onHide = function () {
936
+ if (document.visibilityState === 'hidden') flush(false)
937
+ }
938
+ var onPageHide = function () {
939
+ flush(true)
940
+ }
941
+ /** The config form saved: pick the new allowlist up without a reload. */
942
+ var onConfigChanged = function () {
943
+ refresh()
944
+ }
945
+ document.addEventListener('visibilitychange', onHide)
946
+ window.addEventListener('pagehide', onPageHide)
947
+ window.addEventListener(CONFIG_EVENT, onConfigChanged)
948
+
949
+ refresh()
950
+
951
+ return function () {
952
+ if (originals !== undefined) {
953
+ proto.setItem = originals.setItem
954
+ proto.removeItem = originals.removeItem
955
+ proto.clear = originals.clear
956
+ }
957
+ document.removeEventListener('visibilitychange', onHide)
958
+ window.removeEventListener('pagehide', onPageHide)
959
+ window.removeEventListener(CONFIG_EVENT, onConfigChanged)
960
+ if (state.timer !== undefined) clearTimeout(state.timer)
961
+ if (state.retryTimer !== undefined) clearTimeout(state.retryTimer)
962
+ window[GUARD] = false
963
+ flush(false)
964
+ }
965
+ }, 'localstate-sync: browser capture')
966
+ },
967
+ }
968
+ },
969
+ })