@we-debug/miniprogram 0.49.1 → 0.50.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.
@@ -0,0 +1,240 @@
1
+ const MAX_TEXT_LENGTH = 100 * 1024;
2
+
3
+ export const TYPE_FILTERS = [
4
+ { key: 'all', label: 'All' },
5
+ { key: 'request', label: 'Fetch/XHR' },
6
+ { key: 'downloadFile', label: 'Download' },
7
+ { key: 'uploadFile', label: 'Upload' }
8
+ ];
9
+
10
+ export const DETAIL_TABS = ['Headers', 'Payload', 'Preview', 'Response', 'Timing'];
11
+
12
+ const isPlainObject = v => Object.prototype.toString.call(v) === '[object Object]';
13
+
14
+ export function formatSize(bytes) {
15
+ if (!bytes) return '0 B';
16
+ if (bytes < 1000) return bytes + ' B';
17
+ if (bytes < 1000 * 1000) return (bytes / 1000).toFixed(1) + ' kB';
18
+ return (bytes / (1000 * 1000)).toFixed(1) + ' MB';
19
+ }
20
+
21
+ export function formatTime(ms) {
22
+ if (ms < 1000) return Math.round(ms) + ' ms';
23
+ return (ms / 1000).toFixed(2) + ' s';
24
+ }
25
+
26
+ function pad(n, len = 2) {
27
+ let s = String(n);
28
+ while (s.length < len) s = '0' + s;
29
+ return s;
30
+ }
31
+
32
+ export function formatClock(ts) {
33
+ if (!ts) return '-';
34
+ const d = new Date(ts);
35
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;
36
+ }
37
+
38
+ export function parseUrl(url = '') {
39
+ const match = url.match(/^([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)([^?#]*)(\?[^#]*)?/i);
40
+ if (!match) {
41
+ return { origin: '', host: '', path: url, query: '' };
42
+ }
43
+ const [, protocol = '', host = '', path = '', query = ''] = match;
44
+ return { origin: protocol + '//' + host, host, path: path || '/', query };
45
+ }
46
+
47
+ export function parseQuery(query = '') {
48
+ return query
49
+ .replace(/^\?/, '')
50
+ .split('&')
51
+ .filter(Boolean)
52
+ .map(pair => {
53
+ const i = pair.indexOf('=');
54
+ const key = i > -1 ? pair.slice(0, i) : pair;
55
+ const value = i > -1 ? pair.slice(i + 1) : '';
56
+ const decode = s => {
57
+ try {
58
+ return decodeURIComponent(s.replace(/\+/g, ' '));
59
+ } catch (e) {
60
+ return s;
61
+ }
62
+ };
63
+ return { key: decode(key), value: decode(value) };
64
+ });
65
+ }
66
+
67
+ function getStatus(record) {
68
+ if (record.status === 'pending') return { text: '(pending)', isError: false };
69
+ if (record.status === 'fail') return { text: '(failed)', isError: true };
70
+ return { text: String(record.statusCode), isError: record.statusCode >= 400 };
71
+ }
72
+
73
+ export function toSummary(record) {
74
+ const { host, path, query } = parseUrl(record.url);
75
+ const segments = path.split('/').filter(Boolean);
76
+ const name = (segments.length ? segments[segments.length - 1] : host || record.url) + query;
77
+ const dir = host + '/' + segments.slice(0, -1).join('/');
78
+ const status = getStatus(record);
79
+
80
+ return {
81
+ id: record.id,
82
+ name,
83
+ dir,
84
+ method: record.method,
85
+ api: record.api,
86
+ statusText: status.text,
87
+ isError: status.isError,
88
+ isPending: record.status === 'pending',
89
+ size: record.status === 'success' ? formatSize(record.size) : '-',
90
+ time: record.status === 'pending' ? 'Pending' : formatTime(record.duration)
91
+ };
92
+ }
93
+
94
+ export function matchFilter(record, type, keyword) {
95
+ if (type !== 'all' && record.api !== type) return false;
96
+ if (!keyword) return true;
97
+ return record.url.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
98
+ }
99
+
100
+ export function toKeyValueList(obj) {
101
+ if (!obj || typeof obj !== 'object') return [];
102
+ return Object.keys(obj).map(key => {
103
+ const v = obj[key];
104
+ return { key, value: typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v) };
105
+ });
106
+ }
107
+
108
+ export function stringify(data) {
109
+ if (data === undefined || data === null) return '';
110
+ if (typeof data === 'string') return data;
111
+ if (data instanceof ArrayBuffer) return `[ArrayBuffer ${data.byteLength} bytes]`;
112
+ try {
113
+ return JSON.stringify(data, null, 2);
114
+ } catch (e) {
115
+ return String(data);
116
+ }
117
+ }
118
+
119
+ export function truncate(text) {
120
+ if (text.length <= MAX_TEXT_LENGTH) return { text, truncated: false };
121
+ return { text: text.slice(0, MAX_TEXT_LENGTH), truncated: true };
122
+ }
123
+
124
+ /**
125
+ * 返回可交给 json-view 渲染的对象,非 JSON 内容返回 null
126
+ */
127
+ export function toJsonPreview(data) {
128
+ if (data && typeof data === 'object' && !(data instanceof ArrayBuffer)) return data;
129
+ if (typeof data === 'string') {
130
+ const trimmed = data.trim();
131
+ if (/^[[{]/.test(trimmed)) {
132
+ try {
133
+ return JSON.parse(trimmed);
134
+ } catch (e) {
135
+ return null;
136
+ }
137
+ }
138
+ }
139
+ return null;
140
+ }
141
+
142
+ function getHeader(headers, name) {
143
+ if (!headers) return undefined;
144
+ const lower = name.toLowerCase();
145
+ const key = Object.keys(headers).find(k => k.toLowerCase() === lower);
146
+ return key ? headers[key] : undefined;
147
+ }
148
+
149
+ function shellQuote(str) {
150
+ return `'${String(str).replace(/'/g, `'\\''`)}'`;
151
+ }
152
+
153
+ export function toCurl(record) {
154
+ const parts = [`curl ${shellQuote(record.url)}`];
155
+
156
+ if (record.api === 'request' && record.method !== 'GET') {
157
+ parts.push(`-X ${shellQuote(record.method)}`);
158
+ }
159
+
160
+ Object.keys(record.requestHeaders || {}).forEach(key => {
161
+ parts.push(`-H ${shellQuote(key + ': ' + record.requestHeaders[key])}`);
162
+ });
163
+
164
+ const data = record.requestData;
165
+ if (record.api === 'uploadFile' && data) {
166
+ Object.keys(data.formData || {}).forEach(key => {
167
+ parts.push(`-F ${shellQuote(key + '=' + data.formData[key])}`);
168
+ });
169
+ parts.push(`-F ${shellQuote(data.name + '=@' + data.filePath)}`);
170
+ } else if (record.api === 'request' && record.method !== 'GET' && data !== undefined) {
171
+ const contentType = String(getHeader(record.requestHeaders, 'Content-Type') || '');
172
+ let body;
173
+ if (typeof data === 'string') {
174
+ body = data;
175
+ } else if (isPlainObject(data) && contentType.indexOf('x-www-form-urlencoded') > -1) {
176
+ body = Object.keys(data)
177
+ .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k]))
178
+ .join('&');
179
+ } else {
180
+ try {
181
+ body = JSON.stringify(data);
182
+ } catch (e) {
183
+ body = String(data);
184
+ }
185
+ }
186
+ if (body) parts.push(`--data-raw ${shellQuote(body)}`);
187
+ }
188
+
189
+ return parts.join(' \\\n ');
190
+ }
191
+
192
+ const TIMING_PHASES = [
193
+ { label: 'DNS Lookup', start: 'domainLookupStart', end: 'domainLookupEnd', color: '#009688' },
194
+ { label: 'Initial connection', start: 'connectStart', end: 'connectEnd', color: '#ff9800' },
195
+ { label: 'SSL', start: 'SSLconnectionStart', end: 'SSLconnectionEnd', color: '#9c27b0' },
196
+ { label: 'Waiting for server response', start: 'requestStart', end: 'responseStart', color: '#4caf50' },
197
+ { label: 'Content Download', start: 'responseStart', end: 'responseEnd', color: '#2196f3' }
198
+ ];
199
+
200
+ /**
201
+ * 根据 wx.request 返回的 profile 计算各阶段耗时
202
+ */
203
+ export function toTimingPhases(profile) {
204
+ if (!profile) return [];
205
+ const base = profile.redirectStart || profile.fetchStart || profile.domainLookupStart || profile.requestStart;
206
+ const total = (profile.responseEnd || 0) - base;
207
+ if (!base || total <= 0) return [];
208
+
209
+ return TIMING_PHASES.map(phase => {
210
+ const start = profile[phase.start];
211
+ const end = profile[phase.end];
212
+ if (!start || !end || end < start) return null;
213
+ return {
214
+ label: phase.label,
215
+ color: phase.color,
216
+ duration: formatTime(end - start),
217
+ left: (((start - base) / total) * 100).toFixed(2),
218
+ width: Math.max(((end - start) / total) * 100, 0.5).toFixed(2)
219
+ };
220
+ }).filter(Boolean);
221
+ }
222
+
223
+ export function toProfileList(profile) {
224
+ if (!profile) return [];
225
+ const keys = [
226
+ 'protocol',
227
+ 'estimate_nettype',
228
+ 'httpRttEstimate',
229
+ 'transportRttEstimate',
230
+ 'rtt',
231
+ 'peerIP',
232
+ 'port',
233
+ 'socketReused',
234
+ 'sendBytesCount',
235
+ 'receivedBytedCount'
236
+ ];
237
+ return keys
238
+ .filter(k => profile[k] !== undefined && profile[k] !== '')
239
+ .map(k => ({ key: k, value: String(profile[k]) }));
240
+ }
@@ -156,24 +156,17 @@ Component({
156
156
  : String(selectedItem.value);
157
157
 
158
158
  // 复制到剪贴板
159
- wx.setClipboardData({
160
- data: valueToCopy,
161
- success: () => {
162
- wx.showToast({
163
- title: '已复制',
164
- icon: 'success',
165
- duration: 1500
166
- });
167
- },
168
- fail: err => {
169
- console.error('TableView: failed to copy value:', err);
170
- wx.showToast({
171
- title: '复制失败',
172
- icon: 'error',
173
- duration: 1500
174
- });
175
- }
176
- });
159
+ const toast = (title, icon) => Debug.silent(() => wx.showToast({ title, icon, duration: 1500 }));
160
+ Debug.silent(() =>
161
+ wx.setClipboardData({
162
+ data: valueToCopy,
163
+ success: () => toast('已复制', 'success'),
164
+ fail: err => {
165
+ console.error('TableView: failed to copy value:', err);
166
+ toast('复制失败', 'error');
167
+ }
168
+ })
169
+ );
177
170
  },
178
171
  addListeners() {
179
172
  const prefix = this.data.prefix;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@we-debug/miniprogram",
3
- "version": "0.49.1",
3
+ "version": "0.50.0",
4
4
  "description": "we-debug miniprogram component",
5
5
  "author": {
6
6
  "name": "dlhandsome"
@@ -26,10 +26,10 @@
26
26
  },
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@we-debug/core": "0.49.1"
29
+ "@we-debug/core": "0.50.0"
30
30
  },
31
31
  "readme": "ERROR: No README data found!",
32
32
  "_id": "@we-debug/core@0.3.5",
33
33
  "_commitid": "6c3f04b",
34
- "gitHead": "1f2133736ec3b000dd5fbb005af01ce80c8e995a"
34
+ "gitHead": "2304486ada029231f6e93b89f7491fe0e5d298c6"
35
35
  }