@capyclaw/scrapling 1.0.2 → 1.1.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/ui/app.js ADDED
@@ -0,0 +1,663 @@
1
+ /**
2
+ * DSH 爬虫工作台前端交互(无框架、无构建,纯浏览器原生能力)。
3
+ *
4
+ * 职责:
5
+ * - 引导三步流程:选目标 → 观察爬取流程回放 → 选择器提取/导出
6
+ * - 所有动态内容用 textContent / createElement 渲染,杜绝 XSS
7
+ * - 错误一律给出「下一步做什么」的提示
8
+ */
9
+ (function () {
10
+ 'use strict'
11
+
12
+ var $ = function (id) { return document.getElementById(id) }
13
+
14
+ var state = {
15
+ crawlId: null,
16
+ crawl: null,
17
+ extracts: null, // { key: { selector, count, values, error? } }
18
+ replayToken: 0,
19
+ }
20
+
21
+ /* ---------------- 演示目标与推荐选择器 ---------------- */
22
+ var DEMO_PRESETS = {
23
+ quotes: [
24
+ { key: '名言', selector: '.quote .text::text' },
25
+ { key: '作者', selector: '.quote .author::text' },
26
+ { key: '标签', selector: '.quote .tag::text' },
27
+ ],
28
+ products: [
29
+ { key: '商品名', selector: '.product .name::text' },
30
+ { key: '价格', selector: '.product .price::text' },
31
+ { key: '评分', selector: '.product .rating::attr(data-score)' },
32
+ ],
33
+ news: [
34
+ { key: '标题', selector: '.article h2 a::text' },
35
+ { key: '链接', selector: '.article h2 a::attr(href)' },
36
+ { key: '日期', selector: '.article .date::attr(datetime)' },
37
+ ],
38
+ 'ext-quotes': [
39
+ { key: 'Quote', selector: '.quote .text::text' },
40
+ { key: 'Author', selector: 'small.author::text' },
41
+ { key: 'Tags', selector: 'a.tag::text' },
42
+ ],
43
+ }
44
+
45
+ var STEP_ICONS = {
46
+ url: '🧭', request: '📤', response: '📥', body: '📄',
47
+ dom: '🌳', extract: '🔍', done: '✅', mode: '⚠️',
48
+ }
49
+
50
+ /* ---------------- 健康检查 ---------------- */
51
+ function refreshHealth() {
52
+ fetch('/healthz').then(function (r) { return r.json() }).then(function (h) {
53
+ var pill = $('health-pill')
54
+ if (h.ok) {
55
+ pill.className = 'pill pill-ok'
56
+ pill.textContent = '服务正常 · 已爬 ' + (h.crawls || 0) + ' 次'
57
+ } else {
58
+ throw new Error('not ok')
59
+ }
60
+ }).catch(function () {
61
+ var pill = $('health-pill')
62
+ pill.className = 'pill pill-bad'
63
+ pill.textContent = '服务异常 · 请重启插件'
64
+ })
65
+ }
66
+
67
+ /* ---------------- 工具 ---------------- */
68
+ function normalizeUrl(raw) {
69
+ var text = String(raw || '').trim()
70
+ if (!text) return null
71
+ if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(text)) text = 'http://' + text
72
+ try {
73
+ var u = new URL(text)
74
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null
75
+ return u.href
76
+ } catch (e) {
77
+ return null
78
+ }
79
+ }
80
+
81
+ function fmtBytes(n) {
82
+ if (!n) return '0 B'
83
+ if (n < 1024) return n + ' B'
84
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'
85
+ return (n / 1024 / 1024).toFixed(2) + ' MB'
86
+ }
87
+
88
+ function fmtTime(ts) {
89
+ var d = new Date(ts)
90
+ var pad = function (x) { return String(x).padStart(2, '0') }
91
+ return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
92
+ }
93
+
94
+ function statusClass(status) {
95
+ if (status >= 200 && status < 300) return 'status-2xx'
96
+ if (status >= 300 && status < 400) return 'status-3xx'
97
+ if (status >= 400) return 'status-4xx'
98
+ return 'status-0'
99
+ }
100
+
101
+ function apiError(payload, fallback) {
102
+ var err = (payload && payload.error) || {}
103
+ return { message: err.message || fallback || '请求失败', hint: err.hint || '' }
104
+ }
105
+
106
+ function showCard(id) {
107
+ var el = $(id)
108
+ if (el) el.classList.remove('card-hidden')
109
+ }
110
+
111
+ /* ---------------- 第一步:目标 ---------------- */
112
+ function currentSelectors() {
113
+ var rows = []
114
+ document.querySelectorAll('.selector-row').forEach(function (row) {
115
+ var key = row.querySelector('.key-input').value.trim()
116
+ var sel = row.querySelector('.sel-input').value.trim()
117
+ if (sel) rows.push({ key: key || ('字段' + (rows.length + 1)), selector: sel })
118
+ })
119
+ return rows
120
+ }
121
+
122
+ function setSelectorRows(presets) {
123
+ var wrap = $('selector-rows')
124
+ wrap.textContent = ''
125
+ var list = presets && presets.length ? presets : [{ key: '', selector: '' }]
126
+ list.forEach(function (p) { wrap.appendChild(buildSelectorRow(p.key, p.selector)) })
127
+ }
128
+
129
+ function buildSelectorRow(key, selector) {
130
+ var row = document.createElement('div')
131
+ row.className = 'selector-row'
132
+
133
+ var keyInput = document.createElement('input')
134
+ keyInput.className = 'key-input'
135
+ keyInput.type = 'text'
136
+ keyInput.placeholder = '字段名(如:价格)'
137
+ keyInput.value = key || ''
138
+
139
+ var selInput = document.createElement('input')
140
+ selInput.className = 'sel-input'
141
+ selInput.type = 'text'
142
+ selInput.placeholder = 'CSS 选择器(如:.price::text)'
143
+ selInput.value = selector || ''
144
+
145
+ var remove = document.createElement('button')
146
+ remove.type = 'button'
147
+ remove.className = 'remove-btn'
148
+ remove.title = '删除这个字段'
149
+ remove.textContent = '✕'
150
+ remove.addEventListener('click', function () {
151
+ row.remove()
152
+ if (!document.querySelector('.selector-row')) setSelectorRows([])
153
+ })
154
+
155
+ row.append(keyInput, selInput, remove)
156
+ return row
157
+ }
158
+
159
+ document.querySelectorAll('#demo-chips .chip').forEach(function (chip) {
160
+ chip.addEventListener('click', function () {
161
+ var url = chip.getAttribute('data-url')
162
+ if (url.charAt(0) === '/') url = location.origin + url
163
+ $('url-input').value = url
164
+ $('url-input').classList.remove('invalid')
165
+ setSelectorRows(DEMO_PRESETS[chip.getAttribute('data-kind')] || [])
166
+ })
167
+ })
168
+
169
+ $('add-field-btn').addEventListener('click', function () {
170
+ $('selector-rows').appendChild(buildSelectorRow('', ''))
171
+ })
172
+
173
+ $('crawl-form').addEventListener('submit', function (event) {
174
+ event.preventDefault()
175
+ var input = $('url-input')
176
+ var url = normalizeUrl(input.value)
177
+ if (!url) {
178
+ input.classList.add('invalid')
179
+ input.focus()
180
+ return
181
+ }
182
+ input.classList.remove('invalid')
183
+ input.value = url
184
+ runCrawl(url)
185
+ })
186
+
187
+ function runCrawl(url) {
188
+ var btn = $('crawl-btn')
189
+ btn.disabled = true
190
+ btn.textContent = '爬取中…'
191
+
192
+ var body = {
193
+ url: url,
194
+ timeoutMs: Number($('timeout-input').value) || 20000,
195
+ selectors: currentSelectors(),
196
+ }
197
+ var ua = $('ua-input').value.trim()
198
+ if (ua) body.userAgent = ua
199
+
200
+ fetch('/api/crawl', {
201
+ method: 'POST',
202
+ headers: { 'content-type': 'application/json' },
203
+ body: JSON.stringify(body),
204
+ }).then(function (r) { return r.json() }).then(function (payload) {
205
+ if (!payload.crawl) throw apiError(payload, '爬取失败')
206
+ state.crawl = payload.crawl
207
+ state.crawlId = payload.crawl.id
208
+ state.extracts = payload.crawl.extracts
209
+ showCard('card-pipeline')
210
+ showCard('card-extract')
211
+ showCard('card-history')
212
+ resetExtractBox()
213
+ replaySteps(payload.crawl.steps, function () {
214
+ if (payload.crawl.error) showErrorBanner(payload.crawl.error)
215
+ else hideErrorBanner()
216
+ renderSummary(payload.crawl)
217
+ renderRawHtml(payload.crawl.htmlPreview || '')
218
+ if (state.extracts) renderExtracts(state.extracts, payload.crawl.id)
219
+ refreshHistory()
220
+ refreshHealth()
221
+ $('card-pipeline').scrollIntoView({ behavior: 'smooth', block: 'start' })
222
+ })
223
+ }).catch(function (error) {
224
+ showCard('card-pipeline')
225
+ showErrorBanner({ message: error.message || '网络请求失败', hint: error.hint || '请确认工作台服务还在运行(右上角状态灯),然后重试。' })
226
+ }).finally(function () {
227
+ btn.disabled = false
228
+ btn.textContent = '开始爬取'
229
+ })
230
+ }
231
+
232
+ /* ---------------- 第二步:流程回放 ---------------- */
233
+ function buildStepElement(step) {
234
+ var li = document.createElement('li')
235
+ li.className = 'step'
236
+ li.dataset.stepId = step.id || ''
237
+
238
+ var icon = document.createElement('span')
239
+ icon.className = 'step-icon'
240
+
241
+ var bodyEl = document.createElement('div')
242
+ bodyEl.className = 'step-body'
243
+
244
+ var label = document.createElement('div')
245
+ label.className = 'step-label'
246
+
247
+ var detail = document.createElement('div')
248
+ detail.className = 'step-detail'
249
+
250
+ bodyEl.append(label, detail)
251
+
252
+ var ms = document.createElement('span')
253
+ ms.className = 'step-ms'
254
+
255
+ li.append(icon, bodyEl, ms)
256
+ return li
257
+ }
258
+
259
+ function setStepState(li, phase, step) {
260
+ li.className = 'step step-' + phase
261
+ var icon = li.querySelector('.step-icon')
262
+ var label = li.querySelector('.step-label')
263
+ var detail = li.querySelector('.step-detail')
264
+ var ms = li.querySelector('.step-ms')
265
+ label.textContent = step.label
266
+ detail.textContent = step.detail || ''
267
+ if (phase === 'active') {
268
+ icon.textContent = '⏳'
269
+ ms.textContent = '…'
270
+ } else {
271
+ icon.textContent = STEP_ICONS[step.id] || '•'
272
+ if (phase === 'skip') {
273
+ ms.textContent = '跳过'
274
+ } else if (typeof step.ms === 'number') {
275
+ ms.textContent = ''
276
+ var b = document.createElement('b')
277
+ if (step.ms >= 1000) b.textContent = (step.ms / 1000).toFixed(2) + ' s'
278
+ else if (step.ms < 1) b.textContent = '<1 ms'
279
+ else b.textContent = Math.round(step.ms) + ' ms'
280
+ ms.appendChild(b)
281
+ }
282
+ if (phase === 'done') icon.textContent = '✔'
283
+ if (phase === 'warn') icon.textContent = '⚠️'
284
+ if (phase === 'error') icon.textContent = '✖'
285
+ }
286
+ }
287
+
288
+ /* 按真实时间轴回放(每步回放时长压缩到 0.12s–0.9s,观感与真实兼顾) */
289
+ function replaySteps(steps, onDone) {
290
+ var token = ++state.replayToken
291
+ var pipeline = $('pipeline')
292
+ pipeline.textContent = ''
293
+ var elements = (steps || []).map(function (step) {
294
+ var li = buildStepElement(step)
295
+ pipeline.appendChild(li)
296
+ return li
297
+ })
298
+ var index = 0
299
+ var hasError = false
300
+
301
+ function next() {
302
+ if (token !== state.replayToken) return
303
+ if (index >= elements.length) { if (onDone) onDone(); return }
304
+ var step = steps[index]
305
+ var li = elements[index]
306
+ if (hasError) {
307
+ setStepState(li, 'skip', { label: step.label, detail: '已中止' })
308
+ index++
309
+ setTimeout(next, 60)
310
+ return
311
+ }
312
+ setStepState(li, 'active', step)
313
+ li.scrollIntoView({ block: 'nearest' })
314
+ var delay = Math.min(Math.max(step.ms || 0, 150), 900)
315
+ setTimeout(function () {
316
+ if (token !== state.replayToken) return
317
+ var phase = step.status === 'error' ? 'error' : step.status === 'warn' ? 'warn' : step.status === 'skip' ? 'skip' : 'done'
318
+ if (step.status === 'error') hasError = true
319
+ setStepState(li, phase, step)
320
+ index++
321
+ setTimeout(next, 140)
322
+ }, delay)
323
+ }
324
+ next()
325
+ }
326
+
327
+ function showErrorBanner(error) {
328
+ var banner = $('crawl-error')
329
+ banner.classList.remove('banner-hidden')
330
+ banner.textContent = ''
331
+ var b = document.createElement('b')
332
+ b.textContent = '✖ ' + error.message
333
+ banner.appendChild(b)
334
+ if (error.hint) {
335
+ var hint = document.createElement('span')
336
+ hint.className = 'hint'
337
+ hint.textContent = '下一步:' + error.hint
338
+ banner.appendChild(hint)
339
+ }
340
+ }
341
+
342
+ function hideErrorBanner() {
343
+ $('crawl-error').classList.add('banner-hidden')
344
+ }
345
+
346
+ /* 新爬取/切历史时清掉上一次的数据表,避免旧数据误导 */
347
+ function resetExtractBox() {
348
+ $('extract-result').classList.add('result-hidden')
349
+ $('result-table-wrap').textContent = ''
350
+ $('result-json').textContent = ''
351
+ $('result-note').textContent = ''
352
+ state.lastExport = null
353
+ }
354
+
355
+ function renderSummary(crawl) {
356
+ var box = $('page-summary')
357
+ box.classList.remove('summary-hidden')
358
+ box.textContent = ''
359
+
360
+ function item(k, vContent) {
361
+ var el = document.createElement('div')
362
+ el.className = 'summary-item'
363
+ var key = document.createElement('div')
364
+ key.className = 'k'
365
+ key.textContent = k
366
+ var val = document.createElement('div')
367
+ val.className = 'v'
368
+ if (vContent instanceof Node) val.appendChild(vContent)
369
+ else val.textContent = vContent
370
+ el.append(key, val)
371
+ return el
372
+ }
373
+
374
+ var status = document.createElement('span')
375
+ status.className = 'status-badge ' + statusClass(crawl.status)
376
+ status.textContent = 'HTTP ' + crawl.status
377
+ box.appendChild(item('状态', status))
378
+ box.appendChild(item('页面标题', crawl.title || '(无标题)'))
379
+ box.appendChild(item('内容大小', fmtBytes(crawl.bytes)))
380
+ if (crawl.stats) box.appendChild(item('元素数量', crawl.stats.elements + ' 个'))
381
+ if (crawl.stats) box.appendChild(item('文档深度', String(crawl.stats.maxDepth)))
382
+ box.appendChild(item('总耗时', (crawl.totalMs / 1000).toFixed(2) + ' s'))
383
+ if (crawl.finalUrl && crawl.finalUrl !== crawl.url) box.appendChild(item('最终地址(重定向后)', crawl.finalUrl))
384
+ }
385
+
386
+ function renderRawHtml(html) {
387
+ $('raw-html-pre').textContent = html ? html.slice(0, 40000) : '(无内容)'
388
+ }
389
+
390
+ /* ---------------- 第三步:提取 ---------------- */
391
+ $('extract-btn').addEventListener('click', function () {
392
+ var selectors = currentSelectors()
393
+ if (!selectors.length) {
394
+ alert('请先填写至少一个 CSS 选择器。小提示:点上面的演示目标会自动配好示例选择器。')
395
+ return
396
+ }
397
+ if (!state.crawlId) {
398
+ alert('请先完成一次爬取(第一步),再提取数据。')
399
+ return
400
+ }
401
+ var btn = $('extract-btn')
402
+ btn.disabled = true
403
+ btn.textContent = '提取中…'
404
+ fetch('/api/extract', {
405
+ method: 'POST',
406
+ headers: { 'content-type': 'application/json' },
407
+ body: JSON.stringify({ crawlId: state.crawlId, selectors: selectors }),
408
+ }).then(function (r) { return r.json() }).then(function (payload) {
409
+ if (!payload.ok) throw apiError(payload, '提取失败')
410
+ state.extracts = payload.results
411
+ renderExtracts(payload.results, state.crawlId)
412
+ }).catch(function (error) {
413
+ alert('提取失败:' + error.message + (error.hint ? '\n\n下一步:' + error.hint : ''))
414
+ }).finally(function () {
415
+ btn.disabled = false
416
+ btn.textContent = '提取数据'
417
+ })
418
+ })
419
+
420
+ function extractColumns(results) {
421
+ return Object.keys(results)
422
+ }
423
+
424
+ function renderExtracts(results, crawlId) {
425
+ var box = $('extract-result')
426
+ box.classList.remove('result-hidden')
427
+ var keys = extractColumns(results)
428
+ var total = keys.reduce(function (sum, k) { return sum + (results[k].count || 0) }, 0)
429
+
430
+ /* 表格视图 */
431
+ var tableWrap = $('result-table-wrap')
432
+ tableWrap.textContent = ''
433
+ if (!total) {
434
+ var empty = document.createElement('p')
435
+ empty.className = 'result-note'
436
+ empty.textContent = '没有抓到数据。常见原因:选择器写错了,或页面里确实没有这个元素。可以先展开「原始 HTML」确认写法。'
437
+ tableWrap.appendChild(empty)
438
+ } else {
439
+ var table = document.createElement('table')
440
+ table.className = 'data'
441
+ var thead = document.createElement('thead')
442
+ var headRow = document.createElement('tr')
443
+ keys.forEach(function (k) {
444
+ var th = document.createElement('th')
445
+ th.textContent = k + '(' + results[k].count + ')'
446
+ headRow.appendChild(th)
447
+ })
448
+ thead.appendChild(headRow)
449
+ table.appendChild(thead)
450
+
451
+ var maxRows = keys.reduce(function (m, k) { return Math.max(m, results[k].values.length) }, 0)
452
+ /* 渲染上限:超大结果集只画前 500 行,导出仍含全部数据 */
453
+ var renderRows = Math.min(maxRows, 500)
454
+ var tbody = document.createElement('tbody')
455
+ for (var i = 0; i < renderRows; i++) {
456
+ var tr = document.createElement('tr')
457
+ keys.forEach(function (k) {
458
+ var td = document.createElement('td')
459
+ var cell = results[k].values[i]
460
+ if (cell === undefined) {
461
+ td.textContent = '—'
462
+ td.style.color = '#aaa'
463
+ } else {
464
+ var text = String(cell)
465
+ td.textContent = text.length > 300 ? text.slice(0, 300) + '…' : text
466
+ if (text.length > 300) td.title = text
467
+ }
468
+ tr.appendChild(td)
469
+ })
470
+ tbody.appendChild(tr)
471
+ }
472
+ table.appendChild(tbody)
473
+
474
+ var wrap = document.createElement('div')
475
+ wrap.className = 'table-wrap'
476
+ wrap.appendChild(table)
477
+ tableWrap.appendChild(wrap)
478
+ }
479
+
480
+ /* JSON 视图 */
481
+ var json = {}
482
+ keys.forEach(function (k) {
483
+ json[k] = results[k].error ? { error: results[k].error } : results[k].values
484
+ })
485
+ $('result-json').textContent = JSON.stringify(json, null, 2)
486
+
487
+ /* 备注行 */
488
+ var maxRowsAll = keys.reduce(function (m, k) { return Math.max(m, results[k].values.length) }, 0)
489
+ var badKeys = keys.filter(function (k) { return results[k].error })
490
+ var note = $('result-note')
491
+ note.textContent = crawlId
492
+ ? '记录 ' + crawlId + ' · ' + keys.length + ' 个字段 · 共 ' + total + ' 条数据'
493
+ + (maxRowsAll > 500 ? ' · 表格仅显示前 500 行(导出的 CSV/JSON 包含全部 ' + total + ' 条)' : '')
494
+ + (badKeys.length ? ' · ⚠️ ' + badKeys.length + ' 个字段选择器有误(见表格标注)' : '')
495
+ : ''
496
+ if (badKeys.length) {
497
+ badKeys.forEach(function (k) {
498
+ var p = document.createElement('div')
499
+ p.textContent = '⚠️ 「' + k + '」' + results[k].error
500
+ note.appendChild(document.createElement('br'))
501
+ note.appendChild(p)
502
+ })
503
+ }
504
+ state.lastExport = { json: json, keys: keys, results: results }
505
+ }
506
+
507
+ /* 结果视图切换 */
508
+ document.querySelectorAll('.result-tabs .tab').forEach(function (tab) {
509
+ tab.addEventListener('click', function () {
510
+ document.querySelectorAll('.result-tabs .tab').forEach(function (t) { t.classList.remove('tab-active') })
511
+ tab.classList.add('tab-active')
512
+ var isTable = tab.dataset.tab === 'table'
513
+ $('result-table-wrap').hidden = !isTable
514
+ $('result-json').hidden = isTable
515
+ })
516
+ })
517
+
518
+ /* 导出与复制 */
519
+ function downloadFile(name, content, type) {
520
+ var blob = new Blob([content], { type: type })
521
+ var a = document.createElement('a')
522
+ a.href = URL.createObjectURL(blob)
523
+ a.download = name
524
+ a.click()
525
+ setTimeout(function () { URL.revokeObjectURL(a.href) }, 5000)
526
+ }
527
+
528
+ function exportData() {
529
+ if (!state.lastExport) return null
530
+ return state.lastExport
531
+ }
532
+
533
+ $('copy-json-btn').addEventListener('click', function () {
534
+ var data = exportData()
535
+ if (!data) return
536
+ var text = JSON.stringify(data.json, null, 2)
537
+ var btn = $('copy-json-btn')
538
+ var done = function () {
539
+ btn.textContent = '✓ 已复制'
540
+ setTimeout(function () { btn.textContent = '复制 JSON' }, 1600)
541
+ }
542
+ if (navigator.clipboard && navigator.clipboard.writeText) {
543
+ navigator.clipboard.writeText(text).then(done, function () { fallbackCopy(text, done) })
544
+ } else {
545
+ fallbackCopy(text, done)
546
+ }
547
+ })
548
+
549
+ function fallbackCopy(text, done) {
550
+ var ta = document.createElement('textarea')
551
+ ta.value = text
552
+ document.body.appendChild(ta)
553
+ ta.select()
554
+ try { document.execCommand('copy'); done() } catch (e) { alert('复制失败,请手动在 JSON 标签页里选择复制。') }
555
+ ta.remove()
556
+ }
557
+
558
+ $('download-json-btn').addEventListener('click', function () {
559
+ var data = exportData()
560
+ if (!data) return
561
+ var text = JSON.stringify(data.json, null, 2)
562
+ downloadFile('dsh-scrapling-' + (state.crawlId || 'data') + '.json', text, 'application/json;charset=utf-8')
563
+ })
564
+
565
+ $('download-csv-btn').addEventListener('click', function () {
566
+ var data = exportData()
567
+ if (!data) return
568
+ var keys = data.keys
569
+ var maxRows = keys.reduce(function (m, k) { return Math.max(m, data.results[k].values.length) }, 0)
570
+ var esc = function (v) { return '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"' }
571
+ var lines = [keys.map(esc).join(',')]
572
+ for (var i = 0; i < maxRows; i++) {
573
+ lines.push(keys.map(function (k) { return esc(data.results[k].values[i]) }).join(','))
574
+ }
575
+ /* UTF-8 BOM:保证 Excel 直接打开不乱码 */
576
+ downloadFile('dsh-scrapling-' + (state.crawlId || 'data') + '.csv', '\uFEFF' + lines.join('\r\n'), 'text/csv;charset=utf-8')
577
+ })
578
+
579
+ /* ---------------- 历史 ---------------- */
580
+ function refreshHistory() {
581
+ fetch('/api/crawls').then(function (r) { return r.json() }).then(function (payload) {
582
+ if (!payload.ok) throw new Error('history')
583
+ renderHistory(payload.crawls || [])
584
+ }).catch(function () { /* 历史加载失败不打扰主流程 */ })
585
+ }
586
+
587
+ function renderHistory(crawls) {
588
+ var list = $('history-list')
589
+ list.textContent = ''
590
+ if (!crawls.length) {
591
+ var p = document.createElement('p')
592
+ p.className = 'history-empty'
593
+ p.textContent = '还没有爬取记录。'
594
+ list.appendChild(p)
595
+ return
596
+ }
597
+ crawls.slice(0, 12).forEach(function (item) {
598
+ var btn = document.createElement('button')
599
+ btn.type = 'button'
600
+ btn.className = 'history-item'
601
+
602
+ var status = document.createElement('span')
603
+ status.className = 'status-badge ' + statusClass(item.status)
604
+ status.textContent = item.ok ? item.status : (item.status || '✖')
605
+
606
+ var middle = document.createElement('span')
607
+ var url = document.createElement('div')
608
+ url.className = 'history-url'
609
+ url.textContent = item.url
610
+ var meta = document.createElement('div')
611
+ meta.className = 'history-meta'
612
+ meta.textContent = (item.title ? '「' + item.title.slice(0, 24) + '」 · ' : '') + fmtBytes(item.bytes) + ' · ' + (item.totalMs / 1000).toFixed(1) + 's · ' + (item.itemCount || 0) + ' 条数据'
613
+ middle.append(url, meta)
614
+
615
+ var id = document.createElement('span')
616
+ id.className = 'history-time'
617
+ id.textContent = item.id
618
+
619
+ var time = document.createElement('span')
620
+ time.className = 'history-time'
621
+ time.textContent = fmtTime(item.ts)
622
+
623
+ btn.append(status, middle, id, time)
624
+ btn.addEventListener('click', function () { loadHistoryItem(item.id) })
625
+ list.appendChild(btn)
626
+ })
627
+ }
628
+
629
+ function loadHistoryItem(id) {
630
+ fetch('/api/crawls/' + encodeURIComponent(id)).then(function (r) { return r.json() }).then(function (payload) {
631
+ if (!payload.ok) throw apiError(payload, '读取记录失败')
632
+ var crawl = payload.crawl
633
+ state.crawl = crawl
634
+ state.crawlId = crawl.id
635
+ state.extracts = crawl.extracts
636
+ showCard('card-pipeline')
637
+ showCard('card-extract')
638
+ resetExtractBox()
639
+ /* 恢复当时的选择器 */
640
+ if (crawl.extracts) {
641
+ setSelectorRows(Object.keys(crawl.extracts).map(function (k) {
642
+ return { key: k, selector: crawl.extracts[k].selector }
643
+ }))
644
+ }
645
+ replaySteps(crawl.steps, function () {
646
+ if (crawl.error) showErrorBanner(crawl.error)
647
+ else hideErrorBanner()
648
+ renderSummary(crawl)
649
+ renderRawHtml(crawl.htmlPreview || '')
650
+ if (state.extracts) renderExtracts(state.extracts, crawl.id)
651
+ })
652
+ $('card-pipeline').scrollIntoView({ behavior: 'smooth', block: 'start' })
653
+ }).catch(function (error) {
654
+ alert('读取历史失败:' + error.message + (error.hint ? '\n\n下一步:' + error.hint : ''))
655
+ })
656
+ }
657
+
658
+ /* ---------------- 初始化 ---------------- */
659
+ $('footer-origin').textContent = location.origin
660
+ setSelectorRows([])
661
+ refreshHealth()
662
+ setInterval(refreshHealth, 15000)
663
+ })()