@spfx-fast/spfx-workbench 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +240 -2
- package/bin/spfx-workbench-auth.mjs +143 -0
- package/bin/spfx-workbench-capture.mjs +5 -0
- package/bin/spfx-workbench-debug.mjs +155 -0
- package/bin/spfx-workbench-doctor.mjs +2 -0
- package/bin/spfx-workbench-heft-target.mjs +2 -0
- package/bin/spfx-workbench-replay.mjs +2 -0
- package/bin/spfx-workbench.mjs +97 -0
- package/docs/mock-data-and-capture.md +52 -0
- package/docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md +67 -0
- package/fixtures/library-items.synthetic.json +23 -0
- package/index.html +13 -0
- package/package.json +58 -4
- package/scripts/benchmark-capture-import.mjs +50 -0
- package/scripts/benchmark-consumer-hmr.mjs +251 -0
- package/scripts/benchmark-mock-api.mjs +114 -0
- package/scripts/check-tarball-install.mjs +413 -0
- package/scripts/diagnose-consumer.mjs +228 -0
- package/scripts/diff-captures.mjs +452 -0
- package/scripts/import-synthetic-capture.mjs +60 -0
- package/scripts/minimal-playwright-state.mjs +15 -0
- package/scripts/mock-contract.mjs +375 -0
- package/scripts/replay-sharepoint-capture.mjs +123 -0
- package/scripts/resolve-chromium.mjs +22 -0
- package/scripts/resolve-serve-target.mjs +70 -0
- package/scripts/spfx-node-runtime.mjs +19 -0
- package/scripts/watch-sharepoint-capture.mjs +395 -0
- package/scripts/write-local-capture.mjs +121 -0
- package/src/auth-state.mjs +44 -0
- package/src/contracts/sharepoint-rest.d.ts +38 -0
- package/src/contracts/simulator-context.d.ts +38 -0
- package/src/data-source-label.mjs +10 -0
- package/src/format-modified.mjs +8 -0
- package/src/lifecycle-webpart.jsx +43 -0
- package/src/main.jsx +14 -0
- package/src/simulator-context.mjs +94 -0
- package/src/spfx-preview-shims.mjs +21 -0
- package/src/workbench.css +187 -0
- package/src/workbench.jsx +222 -0
- package/vite.config.js +399 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const args = process.argv.slice(2);
|
|
5
|
+
const valueAfter = (flag) => {
|
|
6
|
+
const index = args.indexOf(flag);
|
|
7
|
+
return index < 0 ? undefined : args[index + 1];
|
|
8
|
+
};
|
|
9
|
+
const beforePath = valueAfter('--before');
|
|
10
|
+
const afterPath = valueAfter('--after');
|
|
11
|
+
const summary = args.includes('--summary');
|
|
12
|
+
const capturePath = valueAfter('--capture');
|
|
13
|
+
const baselinePath = valueAfter('--baseline');
|
|
14
|
+
const initiatorsPath = valueAfter('--initiators');
|
|
15
|
+
const includeValues = args.includes('--values') || (summary && !args.includes('--no-values'));
|
|
16
|
+
const includeRawValues = args.includes('--raw-values');
|
|
17
|
+
const limit = Number(valueAfter('--limit') ?? (summary ? 5000 : 30));
|
|
18
|
+
|
|
19
|
+
function readBody(entry, side) {
|
|
20
|
+
const content = entry?.[side]?.content;
|
|
21
|
+
if (!content?.text) return '';
|
|
22
|
+
return content.encoding === 'base64' ? Buffer.from(content.text, 'base64').toString('utf8') : content.text;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readRequestBody(entry) {
|
|
26
|
+
const postData = entry.request?.postData;
|
|
27
|
+
if (typeof postData?.text !== 'string') return '';
|
|
28
|
+
return postData.encoding === 'base64' ? Buffer.from(postData.text, 'base64').toString('utf8') : postData.text;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function queryNames(entry) {
|
|
32
|
+
return [...new Set((entry.request?.queryString ?? []).map(({ name }) => name))].sort();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function urlPath(entry) {
|
|
36
|
+
try {
|
|
37
|
+
const url = new URL(entry.request.url);
|
|
38
|
+
return `${url.host}${url.pathname}`;
|
|
39
|
+
} catch { return '<invalid URL>'; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function stable(value) {
|
|
43
|
+
if (Array.isArray(value)) return value.map(stable);
|
|
44
|
+
if (value && typeof value === 'object') {
|
|
45
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]));
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function jsonValue(text) {
|
|
51
|
+
try { return stable(JSON.parse(text)); } catch { return undefined; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function compactValue(value) {
|
|
55
|
+
if (value === undefined) return { present: false };
|
|
56
|
+
const serialized = JSON.stringify(value);
|
|
57
|
+
const bytes = Buffer.byteLength(serialized);
|
|
58
|
+
if (bytes <= 512) return value;
|
|
59
|
+
return {
|
|
60
|
+
type: Array.isArray(value) ? 'array' : value && typeof value === 'object' ? 'object' : typeof value,
|
|
61
|
+
bytes,
|
|
62
|
+
preview: serialized.slice(0, 256),
|
|
63
|
+
truncated: true,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function changedValues(before, after, root = '$', found = []) {
|
|
68
|
+
if (found.length >= limit || JSON.stringify(before) === JSON.stringify(after)) return found;
|
|
69
|
+
if (before && after && typeof before === 'object' && typeof after === 'object' && Array.isArray(before) === Array.isArray(after)) {
|
|
70
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
71
|
+
for (const key of keys) {
|
|
72
|
+
if (found.length >= limit) break;
|
|
73
|
+
const beforeHas = Object.hasOwn(before, key);
|
|
74
|
+
const afterHas = Object.hasOwn(after, key);
|
|
75
|
+
if (!beforeHas || !afterHas) {
|
|
76
|
+
found.push({
|
|
77
|
+
path: `${root}.${key}`,
|
|
78
|
+
before: beforeHas ? compactValue(before[key]) : { present: false },
|
|
79
|
+
after: afterHas ? compactValue(after[key]) : { present: false },
|
|
80
|
+
});
|
|
81
|
+
} else changedValues(before[key], after[key], `${root}.${key}`, found);
|
|
82
|
+
}
|
|
83
|
+
} else found.push({ path: root, before: compactValue(before), after: compactValue(after) });
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function valueChanges(beforeText, afterText) {
|
|
88
|
+
const before = jsonValue(beforeText);
|
|
89
|
+
const after = jsonValue(afterText);
|
|
90
|
+
if (before !== undefined && after !== undefined) return changedValues(before, after);
|
|
91
|
+
return beforeText === afterText ? [] : [{ path: '$body', before: compactValue(beforeText), after: compactValue(afterText) }];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function entryValues(entry) {
|
|
95
|
+
const requestBody = readRequestBody(entry);
|
|
96
|
+
const responseBody = readBody(entry, 'response');
|
|
97
|
+
const requestJson = jsonValue(requestBody);
|
|
98
|
+
const responseJson = jsonValue(responseBody);
|
|
99
|
+
return {
|
|
100
|
+
requestValue: compactValue(requestJson !== undefined ? requestJson : requestBody || undefined),
|
|
101
|
+
responseValue: compactValue(responseJson !== undefined ? responseJson : responseBody || undefined),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function bodyShape(text) {
|
|
106
|
+
const value = jsonValue(text);
|
|
107
|
+
if (value === undefined) return text ? { type: 'text', bytes: Buffer.byteLength(text) } : undefined;
|
|
108
|
+
const fields = [];
|
|
109
|
+
const visit = (item, path, depth = 0) => {
|
|
110
|
+
if (fields.length >= 64) return;
|
|
111
|
+
if (Array.isArray(item)) {
|
|
112
|
+
fields.push(`${path}:array[${item.length}]`);
|
|
113
|
+
if (item.length && depth < 4) visit(item[0], `${path}[]`, depth + 1);
|
|
114
|
+
} else if (item && typeof item === 'object') {
|
|
115
|
+
fields.push(`${path}:object`);
|
|
116
|
+
if (depth < 4) for (const [key, child] of Object.entries(item).slice(0, 24)) visit(child, `${path}.${key}`, depth + 1);
|
|
117
|
+
} else fields.push(`${path}:${item === null ? 'null' : typeof item}`);
|
|
118
|
+
};
|
|
119
|
+
visit(value, '$');
|
|
120
|
+
return { type: Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value, fields, truncated: fields.length >= 64 };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function changedPaths(before, after, root = '$', found = []) {
|
|
124
|
+
if (found.length >= limit || JSON.stringify(before) === JSON.stringify(after)) return found;
|
|
125
|
+
if (before && after && typeof before === 'object' && typeof after === 'object' && Array.isArray(before) === Array.isArray(after)) {
|
|
126
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
127
|
+
for (const key of keys) {
|
|
128
|
+
if (found.length >= limit) break;
|
|
129
|
+
if (!Object.hasOwn(before, key) || !Object.hasOwn(after, key)) found.push(`${root}.${key}`);
|
|
130
|
+
else changedPaths(before[key], after[key], `${root}.${key}`, found);
|
|
131
|
+
}
|
|
132
|
+
} else found.push(root);
|
|
133
|
+
return found;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function requestKey(entry) {
|
|
137
|
+
return `${entry.request?.method ?? ''}\n${entry.request?.url ?? ''}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function apiOrder(entries) {
|
|
141
|
+
const calls = entries.filter((entry) => ['xhr', 'fetch'].includes(entry._resourceType));
|
|
142
|
+
const occurrences = new Map();
|
|
143
|
+
return calls.map((entry) => {
|
|
144
|
+
const key = requestKey(entry);
|
|
145
|
+
const occurrence = (occurrences.get(key) ?? 0) + 1;
|
|
146
|
+
occurrences.set(key, occurrence);
|
|
147
|
+
return { key, entry, occurrence };
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function orderDescriptor(call, sequence) {
|
|
152
|
+
if (!call) return null;
|
|
153
|
+
return {
|
|
154
|
+
sequence,
|
|
155
|
+
occurrence: call.occurrence,
|
|
156
|
+
method: call.entry.request?.method ?? 'GET',
|
|
157
|
+
path: urlPath(call.entry),
|
|
158
|
+
status: call.entry.response?.status ?? 0,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function groupByRequest(entries) {
|
|
163
|
+
const groups = new Map();
|
|
164
|
+
for (const entry of entries) {
|
|
165
|
+
const key = requestKey(entry);
|
|
166
|
+
const group = groups.get(key) ?? [];
|
|
167
|
+
group.push(entry);
|
|
168
|
+
groups.set(key, group);
|
|
169
|
+
}
|
|
170
|
+
return groups;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function compactEntry(entry) {
|
|
174
|
+
const requestBody = readRequestBody(entry);
|
|
175
|
+
const responseBody = readBody(entry, 'response');
|
|
176
|
+
const queryOptions = queryNames(entry);
|
|
177
|
+
return {
|
|
178
|
+
method: entry.request?.method ?? 'GET',
|
|
179
|
+
path: urlPath(entry),
|
|
180
|
+
...(queryOptions.length ? { queryOptions } : {}),
|
|
181
|
+
status: entry.response?.status ?? 0,
|
|
182
|
+
requestBytes: Buffer.byteLength(requestBody),
|
|
183
|
+
responseBytes: Buffer.byteLength(responseBody),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function routeTemplate(pathname) {
|
|
188
|
+
const apiIndex = pathname.indexOf('/_api/');
|
|
189
|
+
if (apiIndex < 0) return undefined;
|
|
190
|
+
return pathname.slice(apiIndex + '/_api/'.length)
|
|
191
|
+
.replace(/\([^)]*\)/g, '({argument})')
|
|
192
|
+
.replace(/^v2\.1\/sites\/[^/]+/i, 'v2.1/sites/{site}')
|
|
193
|
+
.replace(/^(v2\.1\/drives\/)[^/]+/i, '$1{driveId}')
|
|
194
|
+
.replace(/(\/items\/)[^/]+/ig, '$1{itemId}')
|
|
195
|
+
.replace(/(?:[a-z0-9-]+\.)*sharepoint\.com/ig, '{tenant}')
|
|
196
|
+
.replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/ig, '{id}')
|
|
197
|
+
.replace(/\d{3,}/g, '{id}');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function apiRouteReview(entries, initiatorEntries = [], includeInitiators = false) {
|
|
201
|
+
const routes = new Map();
|
|
202
|
+
const initiatorRoutes = new Map();
|
|
203
|
+
for (const entry of initiatorEntries) {
|
|
204
|
+
if (!['xhr', 'fetch'].includes(String(entry.resourceType ?? '').toLowerCase())) continue;
|
|
205
|
+
let url;
|
|
206
|
+
try { url = new URL(entry.url); } catch { continue; }
|
|
207
|
+
const route = routeTemplate(url.pathname);
|
|
208
|
+
if (!route) continue;
|
|
209
|
+
const key = `${String(entry.method ?? 'GET').toUpperCase()} ${route}`;
|
|
210
|
+
const item = initiatorRoutes.get(key) ?? { calls: 0, withFrames: 0, sources: new Map() };
|
|
211
|
+
item.calls += 1;
|
|
212
|
+
const frame = entry.initiator?.frames?.[0];
|
|
213
|
+
if (frame) {
|
|
214
|
+
item.withFrames += 1;
|
|
215
|
+
let script = '<inline-or-unknown>';
|
|
216
|
+
try { script = basename(new URL(frame.url).pathname) || script; } catch {}
|
|
217
|
+
const source = { script, functionName: frame.functionName || '<anonymous>', lineNumber: frame.lineNumber ?? null };
|
|
218
|
+
const sourceKey = JSON.stringify(source);
|
|
219
|
+
item.sources.set(sourceKey, (item.sources.get(sourceKey) ?? 0) + 1);
|
|
220
|
+
}
|
|
221
|
+
initiatorRoutes.set(key, item);
|
|
222
|
+
}
|
|
223
|
+
let apiSequence = 0;
|
|
224
|
+
entries.forEach((entry) => {
|
|
225
|
+
if (!['xhr', 'fetch'].includes(entry._resourceType)) return;
|
|
226
|
+
apiSequence += 1;
|
|
227
|
+
let url;
|
|
228
|
+
try { url = new URL(entry.request?.url); } catch { return; }
|
|
229
|
+
const route = routeTemplate(url.pathname);
|
|
230
|
+
if (!route) return;
|
|
231
|
+
const key = `${String(entry.request?.method ?? 'GET').toUpperCase()} ${route}`;
|
|
232
|
+
const item = routes.get(key) ?? { method: String(entry.request?.method ?? 'GET').toUpperCase(), route, firstSequence: apiSequence, calls: 0, statuses: {} };
|
|
233
|
+
item.calls += 1;
|
|
234
|
+
const status = String(entry.response?.status ?? 0);
|
|
235
|
+
item.statuses[status] = (item.statuses[status] ?? 0) + 1;
|
|
236
|
+
routes.set(key, item);
|
|
237
|
+
});
|
|
238
|
+
return [...routes.entries()].map(([key, item]) => {
|
|
239
|
+
const evidence = initiatorRoutes.get(key);
|
|
240
|
+
return {
|
|
241
|
+
...item,
|
|
242
|
+
...(includeInitiators ? {
|
|
243
|
+
initiators: {
|
|
244
|
+
observedCalls: evidence?.calls ?? 0,
|
|
245
|
+
withFrames: evidence?.withFrames ?? 0,
|
|
246
|
+
sources: [...(evidence?.sources ?? new Map())].map(([source, calls]) => ({ ...JSON.parse(source), calls })),
|
|
247
|
+
},
|
|
248
|
+
} : {}),
|
|
249
|
+
review: 'unreviewed',
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function routeFamilyCounts(entries) {
|
|
255
|
+
const routes = new Map();
|
|
256
|
+
for (const entry of entries) {
|
|
257
|
+
if (!['xhr', 'fetch'].includes(String(entry._resourceType ?? '').toLowerCase())) continue;
|
|
258
|
+
let url;
|
|
259
|
+
try { url = new URL(entry.request?.url); } catch { continue; }
|
|
260
|
+
const route = routeTemplate(url.pathname);
|
|
261
|
+
if (!route) continue;
|
|
262
|
+
const method = String(entry.request?.method ?? 'GET').toUpperCase();
|
|
263
|
+
const key = `${method} ${route}`;
|
|
264
|
+
routes.set(key, (routes.get(key) ?? 0) + 1);
|
|
265
|
+
}
|
|
266
|
+
return routes;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function routeEvolution(currentEntries, baselineEntries, baselineName) {
|
|
270
|
+
const current = routeFamilyCounts(currentEntries);
|
|
271
|
+
const baseline = routeFamilyCounts(baselineEntries);
|
|
272
|
+
return {
|
|
273
|
+
baseline: baselineName,
|
|
274
|
+
newSinceBaseline: [...current].filter(([key]) => !baseline.has(key)).map(([key, calls]) => ({ routeFamily: key, calls, status: 'new-observation-review-source' })),
|
|
275
|
+
baselineNotObserved: [...baseline].filter(([key]) => !current.has(key)).map(([key, calls]) => ({ routeFamily: key, baselineCalls: calls, status: 'not-observed-in-current-capture' })),
|
|
276
|
+
shared: [...current].filter(([key]) => baseline.has(key)).map(([key, calls]) => ({ routeFamily: key, currentCalls: calls, baselineCalls: baseline.get(key) })),
|
|
277
|
+
note: 'A new route family is a capture difference that needs source review; it does not prove the API is undocumented. A route absent from the current page capture is not evidence that SharePoint removed it.',
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function loadEntries(raw) {
|
|
282
|
+
const entries = JSON.parse(raw)?.log?.entries;
|
|
283
|
+
if (!Array.isArray(entries)) throw new Error('Expected a Playwright HAR capture.');
|
|
284
|
+
return entries;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
288
|
+
process.stdout.write('Usage: spfx-workbench-capture --summary --capture <tenant.har> [--baseline <earlier.har>] [--initiators <tenant-initiators.json>] [--limit <calls>] [--no-values] [--raw-values]\n spfx-workbench-capture --diff --before <earlier.har> --after <latest.har> [--limit <paths>] [--values] [--raw-values]\n');
|
|
289
|
+
} else if (summary) {
|
|
290
|
+
if (!capturePath || !Number.isInteger(limit) || limit < 1 || limit > 10_000) {
|
|
291
|
+
process.stderr.write('Provide --capture and --limit from 1 to 10000 for a HAR summary.\n');
|
|
292
|
+
process.exitCode = 2;
|
|
293
|
+
} else {
|
|
294
|
+
try {
|
|
295
|
+
const [captureText, initiatorsText, baselineText] = await Promise.all([
|
|
296
|
+
readFile(resolve(capturePath), 'utf8'),
|
|
297
|
+
initiatorsPath ? readFile(resolve(initiatorsPath), 'utf8') : undefined,
|
|
298
|
+
baselinePath ? readFile(resolve(baselinePath), 'utf8') : undefined,
|
|
299
|
+
]);
|
|
300
|
+
const entries = loadEntries(captureText);
|
|
301
|
+
const baselineEntries = baselineText ? loadEntries(baselineText) : undefined;
|
|
302
|
+
const initiatorEntries = initiatorsText ? JSON.parse(initiatorsText)?.entries : [];
|
|
303
|
+
if (!Array.isArray(initiatorEntries)) throw new Error('Expected a SharePoint initiator trace.');
|
|
304
|
+
const apiEntries = entries.filter((entry) => ['xhr', 'fetch'].includes(entry._resourceType));
|
|
305
|
+
const occurrences = new Map();
|
|
306
|
+
const calls = apiEntries.slice(0, limit).map((entry, index) => {
|
|
307
|
+
const base = compactEntry(entry);
|
|
308
|
+
const occurrenceKey = `${base.method}\n${base.path}\n${(base.queryOptions ?? []).join('&')}`;
|
|
309
|
+
const occurrence = (occurrences.get(occurrenceKey) ?? 0) + 1;
|
|
310
|
+
occurrences.set(occurrenceKey, occurrence);
|
|
311
|
+
const requestBody = readRequestBody(entry);
|
|
312
|
+
const responseBody = readBody(entry, 'response');
|
|
313
|
+
const call = {
|
|
314
|
+
sequence: index + 1,
|
|
315
|
+
occurrence,
|
|
316
|
+
resourceType: entry._resourceType ?? 'unknown',
|
|
317
|
+
...base,
|
|
318
|
+
...(requestBody ? { requestShape: bodyShape(requestBody) } : {}),
|
|
319
|
+
...(responseBody ? { responseShape: bodyShape(responseBody) } : {}),
|
|
320
|
+
};
|
|
321
|
+
if (includeValues) Object.assign(call, entryValues(entry));
|
|
322
|
+
if (includeRawValues) call.rawBodies = { request: requestBody.slice(0, 1000), response: responseBody.slice(0, 1000) };
|
|
323
|
+
return call;
|
|
324
|
+
});
|
|
325
|
+
process.stdout.write(JSON.stringify({
|
|
326
|
+
schema: 'spfx-workbench-har-summary/v1',
|
|
327
|
+
capture: basename(resolve(capturePath)),
|
|
328
|
+
totalEntries: entries.length,
|
|
329
|
+
apiCalls: apiEntries.length,
|
|
330
|
+
included: calls.length,
|
|
331
|
+
omitted: apiEntries.length - calls.length,
|
|
332
|
+
apiReview: {
|
|
333
|
+
scope: 'SharePoint REST route families only; tenant and site prefixes removed, function arguments redacted',
|
|
334
|
+
note: 'Unreviewed means no source review is recorded by this capture summary; it does not mean the API is undocumented.',
|
|
335
|
+
routes: apiRouteReview(apiEntries, initiatorEntries, Boolean(initiatorsPath)),
|
|
336
|
+
...(baselineEntries ? { evolution: routeEvolution(apiEntries, baselineEntries, basename(resolve(baselinePath))) } : {}),
|
|
337
|
+
},
|
|
338
|
+
calls,
|
|
339
|
+
}) + '\n');
|
|
340
|
+
} catch (error) {
|
|
341
|
+
process.stderr.write(`Capture summary failed: ${error.message}\n`);
|
|
342
|
+
process.exitCode = 1;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
} else if (!beforePath || !afterPath || !Number.isInteger(limit) || limit < 1 || limit > 500) {
|
|
346
|
+
process.stderr.write('Provide --before, --after, and --limit from 1 to 500.\n');
|
|
347
|
+
process.exitCode = 2;
|
|
348
|
+
} else {
|
|
349
|
+
try {
|
|
350
|
+
const [beforeText, afterText] = await Promise.all([
|
|
351
|
+
readFile(resolve(beforePath), 'utf8'),
|
|
352
|
+
readFile(resolve(afterPath), 'utf8'),
|
|
353
|
+
]);
|
|
354
|
+
const beforeEntries = loadEntries(beforeText);
|
|
355
|
+
const afterEntries = loadEntries(afterText);
|
|
356
|
+
const beforeMap = groupByRequest(beforeEntries);
|
|
357
|
+
const afterMap = groupByRequest(afterEntries);
|
|
358
|
+
const beforeOrder = apiOrder(beforeEntries);
|
|
359
|
+
const afterOrder = apiOrder(afterEntries);
|
|
360
|
+
let commonApiPrefix = 0;
|
|
361
|
+
while (commonApiPrefix < beforeOrder.length && commonApiPrefix < afterOrder.length
|
|
362
|
+
&& beforeOrder[commonApiPrefix].key === afterOrder[commonApiPrefix].key) commonApiPrefix += 1;
|
|
363
|
+
const orderChanged = commonApiPrefix !== beforeOrder.length || commonApiPrefix !== afterOrder.length;
|
|
364
|
+
const added = [];
|
|
365
|
+
const removed = [];
|
|
366
|
+
const changed = [];
|
|
367
|
+
let unchanged = 0;
|
|
368
|
+
|
|
369
|
+
for (const [key, afterCalls] of afterMap) {
|
|
370
|
+
const beforeCalls = beforeMap.get(key) ?? [];
|
|
371
|
+
for (let index = 0; index < afterCalls.length; index += 1) {
|
|
372
|
+
const after = afterCalls[index];
|
|
373
|
+
const before = beforeCalls[index];
|
|
374
|
+
if (!before) {
|
|
375
|
+
const entry = compactEntry(after);
|
|
376
|
+
if (includeValues) Object.assign(entry, entryValues(after));
|
|
377
|
+
added.push(entry);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
const oldRequest = before.request?.postData?.text ?? '';
|
|
381
|
+
const newRequest = after.request?.postData?.text ?? '';
|
|
382
|
+
const oldResponse = readBody(before, 'response');
|
|
383
|
+
const newResponse = readBody(after, 'response');
|
|
384
|
+
const oldJson = jsonValue(oldResponse);
|
|
385
|
+
const newJson = jsonValue(newResponse);
|
|
386
|
+
const oldRequestJson = jsonValue(oldRequest);
|
|
387
|
+
const newRequestJson = jsonValue(newRequest);
|
|
388
|
+
const requestPaths = oldRequestJson !== undefined && newRequestJson !== undefined
|
|
389
|
+
? changedPaths(oldRequestJson, newRequestJson)
|
|
390
|
+
: oldRequest === newRequest ? [] : ['$body'];
|
|
391
|
+
const responsePaths = oldJson !== undefined && newJson !== undefined
|
|
392
|
+
? changedPaths(oldJson, newJson)
|
|
393
|
+
: oldResponse === newResponse ? [] : ['$body'];
|
|
394
|
+
if (before.response?.status === after.response?.status && !requestPaths.length && !responsePaths.length) {
|
|
395
|
+
unchanged += 1;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
const entry = {
|
|
399
|
+
method: after.request?.method ?? 'GET',
|
|
400
|
+
path: urlPath(after),
|
|
401
|
+
...(queryNames(after).length ? { queryOptions: queryNames(after) } : {}),
|
|
402
|
+
status: [before.response?.status ?? 0, after.response?.status ?? 0],
|
|
403
|
+
requestBytes: [Buffer.byteLength(oldRequest), Buffer.byteLength(newRequest)],
|
|
404
|
+
responseBytes: [Buffer.byteLength(oldResponse), Buffer.byteLength(newResponse)],
|
|
405
|
+
requestChangedPaths: requestPaths.slice(0, limit),
|
|
406
|
+
responseChangedPaths: responsePaths.slice(0, limit),
|
|
407
|
+
};
|
|
408
|
+
if (includeValues) {
|
|
409
|
+
entry.requestChanges = valueChanges(oldRequest, newRequest);
|
|
410
|
+
entry.responseChanges = valueChanges(oldResponse, newResponse);
|
|
411
|
+
}
|
|
412
|
+
if (includeRawValues) {
|
|
413
|
+
entry.requestBodies = [oldRequest.slice(0, 1000), newRequest.slice(0, 1000)];
|
|
414
|
+
entry.responseBodies = [oldResponse.slice(0, 1000), newResponse.slice(0, 1000)];
|
|
415
|
+
}
|
|
416
|
+
changed.push(entry);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
for (const [key, beforeCalls] of beforeMap) {
|
|
420
|
+
const afterCount = afterMap.get(key)?.length ?? 0;
|
|
421
|
+
for (const before of beforeCalls.slice(afterCount)) {
|
|
422
|
+
const entry = compactEntry(before);
|
|
423
|
+
if (includeValues) Object.assign(entry, entryValues(before));
|
|
424
|
+
removed.push(entry);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
process.stdout.write(JSON.stringify({
|
|
429
|
+
schema: 'spfx-workbench-har-diff/v1',
|
|
430
|
+
before: basename(resolve(beforePath)), after: basename(resolve(afterPath)),
|
|
431
|
+
counts: { before: beforeEntries.length, after: afterEntries.length, added: added.length, removed: removed.length, changed: changed.length, unchanged },
|
|
432
|
+
apiOrder: {
|
|
433
|
+
beforeCalls: beforeOrder.length,
|
|
434
|
+
afterCalls: afterOrder.length,
|
|
435
|
+
identical: !orderChanged,
|
|
436
|
+
commonPrefix: commonApiPrefix,
|
|
437
|
+
...(orderChanged ? {
|
|
438
|
+
firstDifference: {
|
|
439
|
+
sequence: commonApiPrefix + 1,
|
|
440
|
+
before: orderDescriptor(beforeOrder[commonApiPrefix], commonApiPrefix + 1),
|
|
441
|
+
after: orderDescriptor(afterOrder[commonApiPrefix], commonApiPrefix + 1),
|
|
442
|
+
},
|
|
443
|
+
} : {}),
|
|
444
|
+
},
|
|
445
|
+
added: added.slice(0, limit), removed: removed.slice(0, limit), changed: changed.slice(0, limit),
|
|
446
|
+
truncated: added.length > limit || removed.length > limit || changed.length > limit,
|
|
447
|
+
}) + '\n');
|
|
448
|
+
} catch (error) {
|
|
449
|
+
process.stderr.write(`Capture diff failed: ${error.message}\n`);
|
|
450
|
+
process.exitCode = 1;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { diffSyntheticCapture, normalizeSyntheticCapture } from './mock-contract.mjs';
|
|
4
|
+
import { writeLocalCapture } from './write-local-capture.mjs';
|
|
5
|
+
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const MAX_CAPTURE_BYTES = 1_000_000;
|
|
8
|
+
const valueAfter = (flag) => {
|
|
9
|
+
const index = args.indexOf(flag);
|
|
10
|
+
return index < 0 ? undefined : args[index + 1];
|
|
11
|
+
};
|
|
12
|
+
const inputPath = valueAfter('--input');
|
|
13
|
+
const name = valueAfter('--name') ?? 'library-items';
|
|
14
|
+
|
|
15
|
+
async function readCaptureInput(path) {
|
|
16
|
+
const handle = await open(path, 'r');
|
|
17
|
+
try {
|
|
18
|
+
const info = await handle.stat();
|
|
19
|
+
if (!info.isFile()) throw new Error('Capture input must be a regular file.');
|
|
20
|
+
if (info.size > MAX_CAPTURE_BYTES) throw new Error('Capture input exceeds the 1 MB limit.');
|
|
21
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
22
|
+
const chunks = [];
|
|
23
|
+
let size = 0;
|
|
24
|
+
while (size < MAX_CAPTURE_BYTES + 1) {
|
|
25
|
+
const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, MAX_CAPTURE_BYTES + 1 - size), size);
|
|
26
|
+
if (!bytesRead) break;
|
|
27
|
+
chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
|
|
28
|
+
size += bytesRead;
|
|
29
|
+
}
|
|
30
|
+
if (size > MAX_CAPTURE_BYTES) throw new Error('Capture input exceeds the 1 MB limit.');
|
|
31
|
+
return Buffer.concat(chunks, size);
|
|
32
|
+
} finally {
|
|
33
|
+
await handle.close();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
38
|
+
process.stdout.write('Usage: spfx-workbench-capture --input <synthetic-capture.json> [--name <safe-name>]\n');
|
|
39
|
+
} else if (!inputPath || !/^[a-z0-9][a-z0-9._-]{0,50}$/i.test(name)) {
|
|
40
|
+
process.stderr.write('Usage: spfx-workbench-capture --input <synthetic-capture.json> [--name <safe-name>]\n');
|
|
41
|
+
process.exitCode = 2;
|
|
42
|
+
} else {
|
|
43
|
+
try {
|
|
44
|
+
const source = await readCaptureInput(resolve(inputPath));
|
|
45
|
+
const input = JSON.parse(source.toString('utf8'));
|
|
46
|
+
const normalized = normalizeSyntheticCapture(input);
|
|
47
|
+
const diff = diffSyntheticCapture(input);
|
|
48
|
+
await writeLocalCapture(normalized, { name });
|
|
49
|
+
process.stdout.write(`Saved sanitized synthetic replay to .spfx-workbench/captures/${name}.json (Git-ignored).\n`);
|
|
50
|
+
process.stdout.write(`Contract diff (${diff.contract}):\n`);
|
|
51
|
+
for (const field of diff.fields) {
|
|
52
|
+
process.stdout.write(` response.body.value[*].${field.name}: retained (${field.sourceOccurrences} source occurrence${field.sourceOccurrences === 1 ? '' : 's'})\n`);
|
|
53
|
+
}
|
|
54
|
+
if (diff.strippedFieldOccurrences) process.stdout.write(` unrecognized response field occurrences: ${diff.strippedFieldOccurrences} stripped\n`);
|
|
55
|
+
if (diff.requestHeadersIgnored) process.stdout.write(' request.headers: ignored\n');
|
|
56
|
+
} catch (error) {
|
|
57
|
+
process.stderr.write(`Capture not imported: ${error.message}\n`);
|
|
58
|
+
process.exitCode = 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Capture only cookies sent to the target URL and localStorage for its origin. */
|
|
2
|
+
export async function minimalPlaywrightState(context, page, targetUrl) {
|
|
3
|
+
const target = new URL(targetUrl);
|
|
4
|
+
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
|
5
|
+
throw new Error('Authentication state target must be an HTTP(S) URL without credentials.');
|
|
6
|
+
}
|
|
7
|
+
const pageUrl = new URL(page.url());
|
|
8
|
+
if (pageUrl.origin !== target.origin) throw new Error('The authenticated browser page did not reach the requested SharePoint origin.');
|
|
9
|
+
const cookies = await context.cookies([target.href]);
|
|
10
|
+
const localStorage = await page.evaluate(() => Object.keys(window.localStorage)
|
|
11
|
+
.map((name) => ({ name, value: window.localStorage.getItem(name) }))
|
|
12
|
+
.filter(({ value }) => value !== null));
|
|
13
|
+
if (!cookies.length && !localStorage.length) throw new Error('No browser authentication state was available for the requested SharePoint origin.');
|
|
14
|
+
return { cookies, origins: localStorage.length ? [{ origin: target.origin, localStorage }] : [] };
|
|
15
|
+
}
|