dsh-chrome-bridge 1.19.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +37 -16
  14. package/download.js +895 -69
  15. package/drag.js +68 -30
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +312 -16
  22. package/i18n/index.js +17 -0
  23. package/i18n/ru.js +312 -16
  24. package/i18n/zh.js +310 -14
  25. package/image-guard.js +13 -6
  26. package/index.js +21 -1073
  27. package/locale/ru.json +7 -0
  28. package/nav.js +56 -10
  29. package/package.json +8 -1
  30. package/panel.js +14 -4
  31. package/refs.js +293 -240
  32. package/setup.js +248 -74
  33. package/tools/click.js +58 -0
  34. package/tools/devtools.js +61 -0
  35. package/tools/dialog.js +22 -0
  36. package/tools/download.js +50 -0
  37. package/tools/drag.js +61 -0
  38. package/tools/eval.js +22 -0
  39. package/tools/fill.js +77 -0
  40. package/tools/handoff.js +40 -0
  41. package/tools/index.js +38 -0
  42. package/tools/input.js +147 -0
  43. package/tools/nav.js +57 -0
  44. package/tools/read.js +87 -0
  45. package/tools/record.js +120 -0
  46. package/tools/screenshot.js +223 -0
  47. package/tools/tabs.js +131 -0
  48. package/tools/wait.js +56 -0
  49. package/vendor/cb +616 -35
  50. package/vendor/extension/_locales/en/messages.json +3 -0
  51. package/vendor/extension/_locales/ru/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  53. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  54. package/vendor/extension/background.js +2 -1969
  55. package/vendor/extension/confirm.css +148 -0
  56. package/vendor/extension/confirm.html +49 -0
  57. package/vendor/extension/confirm.js +188 -0
  58. package/vendor/extension/in-page-cursor.js +599 -0
  59. package/vendor/extension/manifest.json +11 -2
  60. package/vendor/extension/popup.css +99 -5
  61. package/vendor/extension/popup.html +28 -2
  62. package/vendor/extension/popup.js +430 -45
  63. package/vendor/extension/sw/boot.js +111 -0
  64. package/vendor/extension/sw/cdp.js +411 -0
  65. package/vendor/extension/sw/chooser.js +192 -0
  66. package/vendor/extension/sw/confirm.js +608 -0
  67. package/vendor/extension/sw/cursor.js +241 -0
  68. package/vendor/extension/sw/dispatch.js +129 -0
  69. package/vendor/extension/sw/download.js +279 -0
  70. package/vendor/extension/sw/fetch-hub.js +224 -0
  71. package/vendor/extension/sw/frames.js +651 -0
  72. package/vendor/extension/sw/imaging.js +361 -0
  73. package/vendor/extension/sw/native.js +111 -0
  74. package/vendor/extension/sw/net-tools.js +525 -0
  75. package/vendor/extension/sw/ops.js +829 -0
  76. package/vendor/extension/sw/popup-api.js +303 -0
  77. package/vendor/extension/sw/profile.js +166 -0
  78. package/vendor/extension/sw/record.js +494 -0
  79. package/vendor/extension/sw/state.js +161 -0
  80. package/vendor/extension/sw/tabui.js +219 -0
  81. package/vendor/extension/sw/util.js +166 -0
  82. package/vendor/extension/sw/welcome.js +26 -0
  83. package/vendor/extension/sw/windows.js +94 -0
  84. package/vendor/extension/welcome.css +189 -0
  85. package/vendor/extension/welcome.html +70 -0
  86. package/vendor/extension/welcome.js +157 -0
  87. package/vendor/host/host.js +476 -71
  88. package/vendor/in-page-cursor.js +309 -37
  89. package/vendor/skill/SKILL.md +34 -16
package/drag.js CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import { refElementJs } from './refs.js'
15
+ import { tt } from './i18n/index.js'
15
16
 
16
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
17
18
 
@@ -47,7 +48,9 @@ const elementJs = (end) =>
47
48
 
48
49
  const isElementEnd = (end) => hasRef(end) || !!end.selector || !!end.text
49
50
  const describe = (end) =>
50
- hasRef(end) ? `[${end.ref}]` : end.selector || (end.text ? `「${end.text}」` : `(${end.x}, ${end.y})`)
51
+ hasRef(end)
52
+ ? `[${end.ref}]`
53
+ : end.selector || (end.text ? tt('res.drag.quotedText', { text: end.text }) : `(${end.x}, ${end.y})`)
51
54
 
52
55
  /** 一次 eval 算出两端的视口坐标,顺带判断是不是原生拖放。 */
53
56
  const PLAN_JS = (from, to) => `(async () => {
@@ -81,12 +84,15 @@ const NATIVE_JS = (from, to, a, b) => `(() => {
81
84
  bubbles: true, cancelable: true, composed: true, clientX: p.x, clientY: p.y, dataTransfer: dt,
82
85
  }));
83
86
  const A = { x: ${a.x}, y: ${a.y} }, B = { x: ${b.x}, y: ${b.y} };
84
- fire(src, 'dragstart', A);
85
- fire(tgt, 'dragenter', B);
86
- const accepted = !fire(tgt, 'dragover', B); // 页面 preventDefault 了 dragover = 这里能放
87
- fire(tgt, 'drop', B);
88
- fire(src, 'dragend', B);
89
- return { accepted };
87
+ try {
88
+ fire(src, 'dragstart', A);
89
+ fire(tgt, 'dragenter', B);
90
+ const accepted = !fire(tgt, 'dragover', B);
91
+ fire(tgt, 'drop', B);
92
+ return { accepted };
93
+ } finally {
94
+ try { fire(src, 'dragend', B); } catch {}
95
+ }
90
96
  })()`
91
97
 
92
98
  /**
@@ -96,30 +102,44 @@ const NATIVE_JS = (from, to, a, b) => `(() => {
96
102
  */
97
103
  export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
98
104
  const plan = (await call('eval', { tabId, expression: PLAN_JS(from, to), userGesture: false })).value
99
- if (!plan) throw new Error('页面没回话(可能刚跳转,重试一次)')
105
+ if (!plan) throw new Error(tt('err.dragNoAnswer'))
100
106
  if (plan.missing) {
101
107
  const end = plan.missing === 'from' ? from : to
102
- throw new Error(`没找到${plan.missing === 'from' ? '起点' : '终点'} ${describe(end)}` +
103
- (hasRef(end) ? '(编号可能已失效,重新 snapshot)' : ''))
108
+ throw new Error(
109
+ tt('err.dragNotFound', {
110
+ end: plan.missing === 'from' ? tt('which.start') : tt('which.end'),
111
+ desc: describe(end),
112
+ }) + (hasRef(end) ? tt('err.dragRefStale') : ''),
113
+ )
114
+ }
115
+ if (plan.same) {
116
+ throw new Error(tt('err.dragSame', { from: describe(from), to: describe(to) }))
104
117
  }
105
- if (plan.same) throw new Error(`起点 ${describe(from)} 和终点 ${describe(to)} 找到的是同一个元素——换个更具体的写法(ref 或 selector)`)
106
118
  const { a, b } = plan
107
- if (!plan.bIn) throw new Error(`终点 ${describe(to)} 不在当前屏幕里——先滚动让起点和终点都露出来`)
119
+ if (!plan.bIn) throw new Error(tt('err.dragOffscreen', { to: describe(to) }))
108
120
 
109
121
  const cur = async (fn) => {
110
122
  if (!cursor) return 0
111
123
  try { return Number(await fn(cursor)) || 0 } catch { return 0 }
112
124
  }
113
125
  // 光标先滑到起点亮名牌,到位了再按下
114
- if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: `拖拽 ${describe(from)} → ${describe(to)}` }))) + 60)
126
+ if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: tt('res.drag.label', { from: describe(from), to: describe(to) }) }))) + 60)
115
127
 
116
128
  if (plan.native) {
117
- await cur((c) => c.down())
118
- await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
119
- const r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
120
- await cur((c) => c.up())
121
- if (r && r.error) throw new Error('终点那里没有元素')
122
- return `已拖拽 ${describe(from)} → ${describe(to)}(HTML5 拖放${r && r.accepted ? ',目标接受了' : ',但目标没表示接受——看看结果对不对'})`
129
+ let r
130
+ try {
131
+ await cur((c) => c.down())
132
+ await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
133
+ r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
134
+ } finally {
135
+ await cur((c) => c.up())
136
+ }
137
+ if (r && r.error) throw new Error(tt('err.dragNoTarget'))
138
+ return tt('res.drag.doneHtml5', {
139
+ from: describe(from),
140
+ to: describe(to),
141
+ verdict: r && r.accepted ? tt('res.drag.accepted') : tt('res.drag.notAccepted'),
142
+ })
123
143
  }
124
144
 
125
145
  const mouse = (type, p, extra) => call('cdp', {
@@ -128,16 +148,34 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
128
148
  params: { type, x: Math.round(p.x), y: Math.round(p.y), ...extra },
129
149
  })
130
150
  await mouse('mouseMoved', a, { button: 'none', buttons: 0 })
131
- await cur((c) => c.down())
132
- await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
133
- const n = Math.max(2, Math.min(60, Number(steps) || 12))
134
- await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true })) // 光标和真实鼠标一起走
135
- for (let i = 1; i <= n; i++) {
136
- const p = { x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }
137
- await mouse('mouseMoved', p, { button: 'left', buttons: 1 })
138
- await sleep(16)
151
+ let point = a
152
+ let moved = false
153
+ try {
154
+ await cur((c) => c.down())
155
+ await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
156
+ const n = Math.max(2, Math.min(60, Number(steps) || 12))
157
+ await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true }))
158
+ for (let i = 1; i <= n; i++) {
159
+ point = { x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }
160
+ await mouse('mouseMoved', point, { button: 'left', buttons: 1 })
161
+ await sleep(16)
162
+ }
163
+ moved = true
164
+ } finally {
165
+ try {
166
+ await mouse('mouseReleased', point, { button: 'left', buttons: 0, clickCount: 1 })
167
+ } catch (error) {
168
+ if (moved) throw error
169
+ } finally {
170
+ await cur((c) => c.up())
171
+ }
139
172
  }
140
- await mouse('mouseReleased', b, { button: 'left', buttons: 0, clickCount: 1 })
141
- await cur((c) => c.up())
142
- return `已拖拽 ${describe(from)} → ${describe(to)}:(${Math.round(a.x)}, ${Math.round(a.y)}) → (${Math.round(b.x)}, ${Math.round(b.y)})`
173
+ return tt('res.drag.doneCoords', {
174
+ from: describe(from),
175
+ to: describe(to),
176
+ x1: Math.round(a.x),
177
+ y1: Math.round(a.y),
178
+ x2: Math.round(b.x),
179
+ y2: Math.round(b.y),
180
+ })
143
181
  }
@@ -0,0 +1,58 @@
1
+ import { tt } from '../i18n/index.js'
2
+
3
+ // Only the explicit legacy dispatcher error means that the extension lacks this op.
4
+ async function frameOp(call, operation, tabId, args = {}) {
5
+ try {
6
+ return await call(operation, { ...args, tabId })
7
+ } catch (error) {
8
+ if (new RegExp('(?:未知操作|unknown (?:operation|op))\\s*[::]\\s*' + operation + '\\b', 'i').test(error.message)) return null
9
+ throw error
10
+ }
11
+ }
12
+
13
+ // Multiples of 10000 are reserved for overflow of the main document's ref space.
14
+ export const isFrameRef = n => Number(n) >= 10000 && Number(n) % 10000 !== 0
15
+
16
+ export async function frameField(call, tabId, operation, args) {
17
+ const ref = Number(args.ref)
18
+ const reply = await frameOp(call, operation, tabId, { ...args, ref })
19
+ if (!reply || reply.gone) throw new Error(tt('err.refGone', { ref }))
20
+ const result = reply.result
21
+ if (typeof result === 'object' || result === 'ok') return result
22
+ const errors = { disabled: 'err.fieldDisabled', wrong: 'err.fieldWrong', noOption: 'err.selectNoOption' }
23
+ throw new Error(tt(errors[result] || 'err.fieldRejected'))
24
+ }
25
+
26
+ export async function mergeFrameSnapshot(call, tabId, v, scope, query) {
27
+ const paths = v.rows.filter(row => row.crossPath).map(row => row.crossPath)
28
+ if (paths.length) {
29
+ const extra = await frameOp(call, 'frameSnapshot', tabId, { paths, scope, query: query.trim().toLowerCase() })
30
+ const byPath = new Map()
31
+ for (const group of extra?.groups || []) {
32
+ const key = group.path.join('.')
33
+ if (!byPath.has(key)) byPath.set(key, [])
34
+ byPath.get(key).push(...group.rows)
35
+ v.count += group.count
36
+ v.outside += group.outside
37
+ v.capped ||= group.capped
38
+ }
39
+ v.rows = v.rows.flatMap(row => byPath.get(row.crossPath?.join('.')) || (row.line ? [row] : []))
40
+ }
41
+ }
42
+
43
+ export async function mergeFrameTexts(call, tabId, rows) {
44
+ const paths = rows.filter(row => row.cross).map(row => row.path)
45
+ if (!paths.length) return rows
46
+ const extra = await frameOp(call, 'frameTexts', tabId, { paths })
47
+ return rows.flatMap(({ path, ...row }) => {
48
+ if (!row.cross) return [row]
49
+ const matches = extra?.groups?.filter(f => f.path.join('.') === path.join('.'))
50
+ return matches?.length ? matches.map(({ src, text }) => ({ src, text })) : [row]
51
+ }).slice(0, 30)
52
+ }
53
+
54
+ export async function locateFrame(call, tabId, ref) {
55
+ const point = await frameOp(call, 'frameLocate', tabId, { ref })
56
+ if (!point || point.gone) throw new Error(tt('err.refGone', { ref }))
57
+ return point
58
+ }
@@ -0,0 +1,203 @@
1
+ import { tt } from '../i18n/index.js'
2
+
3
+ const MIN_CODE_SIZE = 8
4
+ const CLEAR_CODE = 1 << MIN_CODE_SIZE
5
+ const EOI_CODE = CLEAR_CODE + 1
6
+ const TRANSPARENT_INDEX = 252
7
+ const HASH_SIZE = 8192
8
+ const HASH_MASK = HASH_SIZE - 1
9
+
10
+ function buildUniformPalette() {
11
+ const palette = new Uint8Array(256 * 3)
12
+ for (let r = 0; r < 6; r++) {
13
+ for (let g = 0; g < 7; g++) {
14
+ for (let b = 0; b < 6; b++) {
15
+ const index = (r * 42 + g * 6 + b) * 3
16
+ palette[index] = Math.round(r * 255 / 5)
17
+ palette[index + 1] = Math.round(g * 255 / 6)
18
+ palette[index + 2] = Math.round(b * 255 / 5)
19
+ }
20
+ }
21
+ }
22
+ for (const [index, gray] of [[252, 0], [253, 85], [254, 170], [255, 255]]) {
23
+ palette[index * 3] = palette[index * 3 + 1] = palette[index * 3 + 2] = gray
24
+ }
25
+ return palette
26
+ }
27
+
28
+ const PALETTE = buildUniformPalette()
29
+
30
+ function quantize(r, g, b) {
31
+ const ri = Math.min(5, ((r * 5 + 127) / 255) | 0)
32
+ const gi = Math.min(6, ((g * 6 + 127) / 255) | 0)
33
+ const bi = Math.min(5, ((b * 5 + 127) / 255) | 0)
34
+ return ri * 42 + gi * 6 + bi
35
+ }
36
+
37
+ function bytesOf(value) {
38
+ if (value instanceof Uint8Array) return value
39
+ if (typeof value === 'string') return new Uint8Array(Buffer.from(value, 'base64'))
40
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
41
+ if (value && value.buffer instanceof ArrayBuffer) return new Uint8Array(value.buffer, value.byteOffset || 0, value.byteLength)
42
+ return null
43
+ }
44
+
45
+ function indexedFrame(frame, pixels) {
46
+ const rgba = bytesOf(frame.rgba)
47
+ const rgb = rgba ? null : bytesOf(frame.rgb)
48
+ const out = new Uint8Array(pixels)
49
+ let transparent = false
50
+ if (rgba) {
51
+ if (rgba.length !== pixels * 4) throw new Error(tt('err.gifFrameSize'))
52
+ for (let i = 0, j = 0; j < pixels; i += 4, j++) {
53
+ if (rgba[i + 3] < 128) {
54
+ out[j] = TRANSPARENT_INDEX
55
+ transparent = true
56
+ } else {
57
+ out[j] = quantize(rgba[i], rgba[i + 1], rgba[i + 2])
58
+ }
59
+ }
60
+ } else if (rgb) {
61
+ if (rgb.length !== pixels * 3) throw new Error(tt('err.gifFrameSize'))
62
+ for (let i = 0, j = 0; j < pixels; i += 3, j++) out[j] = quantize(rgb[i], rgb[i + 1], rgb[i + 2])
63
+ } else {
64
+ throw new Error(tt('err.gifFrameSize'))
65
+ }
66
+ return { indices: out, transparent }
67
+ }
68
+
69
+ function hashProbe(keys, values, key) {
70
+ let h = Math.imul(key, 0x9e3779b1) & HASH_MASK
71
+ for (;;) {
72
+ const stored = keys[h]
73
+ if (stored === 0) return { h, found: -1 }
74
+ if (stored === key + 1) return { h, found: values[h] - 1 }
75
+ h = (h + 1) & HASH_MASK
76
+ }
77
+ }
78
+
79
+ function lzwEncode(indices, minCodeSize = MIN_CODE_SIZE) {
80
+ const clear = 1 << minCodeSize
81
+ const eoi = clear + 1
82
+ const keys = new Int32Array(HASH_SIZE)
83
+ const values = new Int32Array(HASH_SIZE)
84
+ const out = []
85
+ let next = eoi + 1
86
+ let codeSize = minCodeSize + 1
87
+ let acc = 0
88
+ let bits = 0
89
+
90
+ const write = (code) => {
91
+ acc |= code << bits
92
+ bits += codeSize
93
+ while (bits >= 8) {
94
+ out.push(acc & 0xff)
95
+ acc >>= 8
96
+ bits -= 8
97
+ }
98
+ }
99
+ const reset = () => {
100
+ keys.fill(0)
101
+ values.fill(0)
102
+ next = eoi + 1
103
+ codeSize = minCodeSize + 1
104
+ }
105
+
106
+ write(clear)
107
+ if (indices.length) {
108
+ let prefix = indices[0]
109
+ for (let i = 1; i < indices.length; i++) {
110
+ const k = indices[i]
111
+ const key = (prefix << 8) | k
112
+ const hit = hashProbe(keys, values, key)
113
+ if (hit.found >= 0) {
114
+ prefix = hit.found
115
+ continue
116
+ }
117
+ write(prefix)
118
+ if (next < 4096) {
119
+ keys[hit.h] = key + 1
120
+ values[hit.h] = next + 1
121
+ next++
122
+ if (next > (1 << codeSize) && codeSize < 12) codeSize++
123
+ } else {
124
+ write(clear)
125
+ reset()
126
+ }
127
+ prefix = k
128
+ }
129
+ write(prefix)
130
+ }
131
+ write(eoi)
132
+ if (bits > 0) out.push(acc & 0xff)
133
+ return Uint8Array.from(out)
134
+ }
135
+
136
+ function pushAscii(parts, text) {
137
+ parts.push(Buffer.from(text, 'ascii'))
138
+ }
139
+
140
+ function pushU16(parts, value) {
141
+ const b = Buffer.allocUnsafe(2)
142
+ b.writeUInt16LE(Math.max(0, Math.min(65535, Math.round(value))), 0)
143
+ parts.push(b)
144
+ }
145
+
146
+ function encodeGif({ width, height, frames, loop = 0 }) {
147
+ width = Math.round(Number(width))
148
+ height = Math.round(Number(height))
149
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 65535 || height > 65535) {
150
+ throw new Error(tt('err.gifSize'))
151
+ }
152
+ if (!Array.isArray(frames) || !frames.length) throw new Error(tt('err.gifFrames'))
153
+ const pixels = width * height
154
+ const prepared = frames.map((frame) => indexedFrame(frame || {}, pixels))
155
+ const hasTransparency = prepared.some(f => f.transparent)
156
+
157
+ const parts = []
158
+ pushAscii(parts, 'GIF89a')
159
+ pushU16(parts, width)
160
+ pushU16(parts, height)
161
+ parts.push(Buffer.from([0xf7, 0, 0]))
162
+ parts.push(Buffer.from(PALETTE.buffer, PALETTE.byteOffset, PALETTE.byteLength))
163
+
164
+ parts.push(Buffer.from([0x21, 0xff, 0x0b]))
165
+ pushAscii(parts, 'NETSCAPE2.0')
166
+ parts.push(Buffer.from([0x03, 0x01]))
167
+ pushU16(parts, Math.max(0, Math.min(65535, Math.round(Number(loop) || 0))))
168
+ parts.push(Buffer.from([0]))
169
+
170
+ for (let i = 0; i < frames.length; i++) {
171
+ const delayCs = Math.max(2, Math.min(65535, Math.round(Number(frames[i] && frames[i].delayCs) || 10)))
172
+ parts.push(Buffer.from([0x21, 0xf9, 0x04, hasTransparency ? 0x05 : 0x00]))
173
+ pushU16(parts, delayCs)
174
+ parts.push(Buffer.from([hasTransparency ? TRANSPARENT_INDEX : 0, 0x00]))
175
+
176
+ parts.push(Buffer.from([0x2c]))
177
+ pushU16(parts, 0)
178
+ pushU16(parts, 0)
179
+ pushU16(parts, width)
180
+ pushU16(parts, height)
181
+ parts.push(Buffer.from([0x00, MIN_CODE_SIZE]))
182
+ const compressed = lzwEncode(prepared[i].indices)
183
+ for (let at = 0; at < compressed.length; at += 255) {
184
+ const end = Math.min(at + 255, compressed.length)
185
+ parts.push(Buffer.from([end - at]))
186
+ parts.push(Buffer.from(compressed.buffer, compressed.byteOffset + at, end - at))
187
+ }
188
+ parts.push(Buffer.from([0]))
189
+ }
190
+ parts.push(Buffer.from([0x3b]))
191
+ return Buffer.concat(parts)
192
+ }
193
+
194
+ export {
195
+ encodeGif,
196
+ lzwEncode,
197
+ quantize,
198
+ PALETTE,
199
+ TRANSPARENT_INDEX,
200
+ MIN_CODE_SIZE,
201
+ CLEAR_CODE,
202
+ EOI_CODE,
203
+ }
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,85 @@
1
+ import { mkdir, open, unlink } from 'node:fs/promises'
2
+ import { t } from '../core/locale.js'
3
+ import { downloadsDir, humanSize, safeName, uniquePath } from '../download.js'
4
+ import { requireExtensionOp } from '../nav.js'
5
+
6
+ async function netOp(call, op, args, timeoutMs) {
7
+ try {
8
+ return await requireExtensionOp(call, op, args, timeoutMs, () => t('err.devtools.extension200'))
9
+ } catch (error) {
10
+ const messages = Object.assign(Object.create(null), {
11
+ MOCK_INVALID: () => t('err.devtools.mockInvalid'),
12
+ MOCK_LIMIT: () => t('err.devtools.mockLimit'),
13
+ HAR_INACTIVE: () => t('err.devtools.harInactive'),
14
+ })
15
+ if (messages[error.message]) throw new Error(messages[error.message](), { cause: error })
16
+ throw error
17
+ }
18
+ }
19
+
20
+ export async function writeHar(dir, filename, har) {
21
+ const base = safeName(String(filename || '').replace(/\.har$/i, '')) || 'network'
22
+ await mkdir(dir, { recursive: true })
23
+ const data = Buffer.from(JSON.stringify(har, null, 2) + '\n')
24
+ for (let i = 0; i < 1000; i++) {
25
+ const file = uniquePath(dir, base + '.har')
26
+ let handle
27
+ try {
28
+ handle = await open(file, 'wx', 0o600)
29
+ } catch (error) {
30
+ if (error.code === 'EEXIST') continue
31
+ throw error
32
+ }
33
+ try {
34
+ if (process.platform !== 'win32') await handle.chmod(0o600)
35
+ await handle.writeFile(data)
36
+ await handle.close()
37
+ return { file, bytes: data.length, count: har.log.entries.length }
38
+ } catch (error) {
39
+ await handle.close().catch(() => {})
40
+ await unlink(file).catch(() => {})
41
+ throw error
42
+ }
43
+ }
44
+ throw new Error(t('err.dlTooManyNames', { dir, name: base + '.har' }))
45
+ }
46
+
47
+ export async function mockHarAction(call, tabId, args, exec) {
48
+ switch (args.action) {
49
+ case 'mock': {
50
+ const { urlPattern, method, status, headers, body, contentType, delayMs, abort } = args
51
+ if (typeof urlPattern !== 'string' || !urlPattern.trim()) throw new Error(t('err.devtools.mockPattern'))
52
+ const result = await netOp(call, 'mockSet', { tabId, urlPattern, method, status, headers, body, contentType, delayMs, abort })
53
+ return t('res.devtools.mockSet', result)
54
+ }
55
+ case 'unmock': {
56
+ const result = await netOp(call, 'mockClear', { tabId, id: args.mockId })
57
+ return t('res.devtools.mockClear', result)
58
+ }
59
+ case 'mocks': {
60
+ const { rules } = await netOp(call, 'mockList', { tabId })
61
+ if (!rules.length) return t('res.devtools.mocksEmpty')
62
+ return [t('res.devtools.mocksCount', { n: rules.length }), ...rules.map(rule =>
63
+ t('res.devtools.mockRule', { ...rule, method: rule.method || '*', seconds: Math.ceil(rule.expiresInMs / 1000) }))].join('\n')
64
+ }
65
+ case 'har_start':
66
+ await netOp(call, 'harStart', { tabId })
67
+ return t('res.devtools.harStart')
68
+ case 'har_export': {
69
+ let dir
70
+ if (args.to === 'workdir') {
71
+ const { sessionCwd } = await import('../core/session.js')
72
+ dir = sessionCwd(exec)
73
+ } else {
74
+ dir = downloadsDir()
75
+ }
76
+ if (!dir) throw new Error(t('err.noWorkdir'))
77
+ const har = await netOp(call, 'harExport', { tabId, includeBodies: !!args.includeBodies, clear: !!args.clear }, 75_000)
78
+ if (har?.log?.version !== '1.2' || !Array.isArray(har.log.entries)) throw new Error(t('err.devtools.harInvalid'))
79
+ const { count, bytes, file } = await writeHar(dir, args.filename, har)
80
+ return t('res.devtools.harSaved', { count, size: humanSize(bytes), file })
81
+ }
82
+ default:
83
+ throw new Error(t('err.unknownAction', { action: args.action }))
84
+ }
85
+ }