@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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +240 -2
  3. package/bin/spfx-workbench-auth.mjs +143 -0
  4. package/bin/spfx-workbench-capture.mjs +5 -0
  5. package/bin/spfx-workbench-debug.mjs +155 -0
  6. package/bin/spfx-workbench-doctor.mjs +2 -0
  7. package/bin/spfx-workbench-heft-target.mjs +2 -0
  8. package/bin/spfx-workbench-replay.mjs +2 -0
  9. package/bin/spfx-workbench.mjs +97 -0
  10. package/docs/mock-data-and-capture.md +52 -0
  11. package/docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md +67 -0
  12. package/fixtures/library-items.synthetic.json +23 -0
  13. package/index.html +13 -0
  14. package/package.json +58 -4
  15. package/scripts/benchmark-capture-import.mjs +50 -0
  16. package/scripts/benchmark-consumer-hmr.mjs +251 -0
  17. package/scripts/benchmark-mock-api.mjs +114 -0
  18. package/scripts/check-tarball-install.mjs +413 -0
  19. package/scripts/diagnose-consumer.mjs +228 -0
  20. package/scripts/diff-captures.mjs +452 -0
  21. package/scripts/import-synthetic-capture.mjs +60 -0
  22. package/scripts/minimal-playwright-state.mjs +15 -0
  23. package/scripts/mock-contract.mjs +375 -0
  24. package/scripts/replay-sharepoint-capture.mjs +123 -0
  25. package/scripts/resolve-chromium.mjs +22 -0
  26. package/scripts/resolve-serve-target.mjs +70 -0
  27. package/scripts/spfx-node-runtime.mjs +19 -0
  28. package/scripts/watch-sharepoint-capture.mjs +395 -0
  29. package/scripts/write-local-capture.mjs +121 -0
  30. package/src/auth-state.mjs +44 -0
  31. package/src/contracts/sharepoint-rest.d.ts +38 -0
  32. package/src/contracts/simulator-context.d.ts +38 -0
  33. package/src/data-source-label.mjs +10 -0
  34. package/src/format-modified.mjs +8 -0
  35. package/src/lifecycle-webpart.jsx +43 -0
  36. package/src/main.jsx +14 -0
  37. package/src/simulator-context.mjs +94 -0
  38. package/src/spfx-preview-shims.mjs +21 -0
  39. package/src/workbench.css +187 -0
  40. package/src/workbench.jsx +222 -0
  41. package/vite.config.js +399 -0
@@ -0,0 +1,375 @@
1
+ const FORMAT = 'spfx-workbench-capture/v1';
2
+ const ROUTE = 'sp-rest-library-items';
3
+ export const MOCK_API_PATH = '/__spfx_workbench/api/library-items';
4
+ export const MOCK_WEB_API_PATH = '/__spfx_workbench/api/web';
5
+ export const MOCK_LISTS_API_PATH = '/__spfx_workbench/api/lists';
6
+ export const MOCK_HAR_API_PATH = '/__spfx_workbench/api/captured';
7
+ export const MOCK_WEB_TITLE = 'Workbench site';
8
+ export const CAPTURED_READ_POST_ROUTES = Object.freeze([
9
+ Object.freeze({ pattern: /\/_api\/web\/SiteUserInfoList\/GetItems\/?$/i, description: '/web/SiteUserInfoList/GetItems' }),
10
+ Object.freeze({ pattern: /\/_api\/web\/GetList\([^/]*\)\/RenderListDataAsStream\/?$/i, description: '/web/GetList(...)/RenderListDataAsStream' }),
11
+ Object.freeze({ pattern: /\/_api\/web\/GetList\([^/]*\)\/RenderExtendedListFormData\([^/]*\)\/?$/i, description: '/web/GetList(...)/RenderExtendedListFormData(...)' }),
12
+ ]);
13
+ export const MOCK_SHAREPOINT_LISTS = Object.freeze([
14
+ Object.freeze({ Id: '11111111-1111-4111-8111-111111111111', Title: 'Workbench Documents', ItemCount: 12 }),
15
+ Object.freeze({ Id: '22222222-2222-4222-8222-222222222222', Title: 'Workbench Media', ItemCount: 7 }),
16
+ ]);
17
+
18
+ function stableBody(value) {
19
+ if (Array.isArray(value)) return value.map(stableBody);
20
+ if (value && typeof value === 'object') {
21
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stableBody(value[key])]));
22
+ }
23
+ return value;
24
+ }
25
+
26
+ function normalizedRequestBody(value) {
27
+ if (typeof value !== 'string' || !value) return null;
28
+ try {
29
+ const parsed = JSON.parse(value);
30
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
31
+ return JSON.stringify(stableBody(parsed));
32
+ } catch { return null; }
33
+ }
34
+
35
+ export function capturedApiRequestKey(method, requestUrl, requestBody = '') {
36
+ let url;
37
+ try { url = new URL(requestUrl); } catch { return null; }
38
+ const apiPathIndex = url.pathname.indexOf('/_api/');
39
+ if (apiPathIndex < 0) return null;
40
+ const normalizedMethod = String(method).toUpperCase();
41
+ if (!['GET', 'POST'].includes(normalizedMethod)) return null;
42
+ const path = url.pathname.slice(apiPathIndex);
43
+ const query = [...url.searchParams.entries()]
44
+ .sort(([nameA, valueA], [nameB, valueB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : valueA < valueB ? -1 : valueA > valueB ? 1 : 0);
45
+ const body = normalizedMethod === 'POST' ? normalizedRequestBody(requestBody) : '';
46
+ if (body === null) return null;
47
+ return `${normalizedMethod}\n${path}\n${JSON.stringify(query)}\n${body}`;
48
+ }
49
+
50
+ export function indexCapturedApiRequests(entries) {
51
+ const index = new Map();
52
+ for (const entry of entries) {
53
+ const request = entry?.request;
54
+ const method = String(request?.method).toUpperCase();
55
+ if (!['GET', 'POST'].includes(method)) continue;
56
+ const postData = request.postData ?? {};
57
+ const body = typeof postData.text === 'string'
58
+ ? postData.encoding === 'base64' ? Buffer.from(postData.text, 'base64').toString('utf8') : postData.text
59
+ : '';
60
+ const key = capturedApiRequestKey(method, request.url, body);
61
+ if (!key) continue;
62
+ const matches = index.get(key) ?? [];
63
+ matches.push(entry);
64
+ index.set(key, matches);
65
+ }
66
+ return index;
67
+ }
68
+
69
+ export function matchCapturedApiRequest(index, method, requestUrl, occurrence = 0, requestBody = '') {
70
+ const matches = index.get(capturedApiRequestKey(method, requestUrl, requestBody));
71
+ return matches?.[Math.min(occurrence, matches.length - 1)] ?? null;
72
+ }
73
+
74
+ const FIELDS = ['Id', 'Title', 'FileLeafRef', 'Modified'];
75
+ const FIELD_SET = new Set(FIELDS);
76
+ const QUERY_OPTIONS = ['$select', '$top'];
77
+ const MAX_ID = 2_147_483_647;
78
+ const MAX_ITEMS = 100;
79
+ const MAX_TOP = 100;
80
+ const DEFAULT_TOP = 25;
81
+ const LIST_ITEMS_PATH = /\/_api\/web\/lists(?:\(guid'[^']+'\)|\/[^/]+)\/items\/?$/i;
82
+ const WEB_METADATA_PATH = /\/_api\/web\/?$/i;
83
+ const SHAREPOINT_LISTS_PATH = /\/_api\/web\/lists\/?$/i;
84
+
85
+ export function isSupportedListItemsPath(path) {
86
+ return LIST_ITEMS_PATH.test(path);
87
+ }
88
+
89
+ export function isSupportedWebMetadataPath(path) {
90
+ return WEB_METADATA_PATH.test(path);
91
+ }
92
+
93
+ export function isSupportedSharePointListsPath(path) {
94
+ return SHAREPOINT_LISTS_PATH.test(path);
95
+ }
96
+
97
+ export const MOCK_COVERAGE = Object.freeze({
98
+ route: MOCK_API_PATH,
99
+ additionalRoutes: [{
100
+ route: MOCK_WEB_API_PATH,
101
+ clientMethod: 'get',
102
+ requestPath: '/_api/web',
103
+ fields: ['Title'],
104
+ queryOptions: ['$select'],
105
+ response: { Title: MOCK_WEB_TITLE },
106
+ source: {
107
+ version: 'SPFx 1.24.1 documentation',
108
+ url: 'https://learn.microsoft.com/en-us/sharepoint/dev/spfx/connect-to-sharepoint#connect-to-sharepoint-api-using-the-sphttpclient',
109
+ basis: 'Microsoft documents SPHttpClient.get on /_api/web?$select=Title and a JSON response with a Title string.',
110
+ },
111
+ unsupported: ['web properties other than Title', 'query options other than $select'],
112
+ }, {
113
+ route: MOCK_LISTS_API_PATH,
114
+ clientMethod: 'get',
115
+ requestPath: '/_api/web/lists',
116
+ fields: ['Id', 'Title', 'ItemCount'],
117
+ queryOptions: ['$select', '$filter', '$orderby'],
118
+ response: { value: MOCK_SHAREPOINT_LISTS },
119
+ source: {
120
+ version: 'Microsoft Learn, updated 2026-10-28',
121
+ url: 'https://learn.microsoft.com/en-us/sharepoint/dev/spfx/copilot/access-data',
122
+ basis: 'Microsoft documents an SPHttpClient GET selecting Id, Title, and ItemCount, filtering Hidden eq false, and ordering by Title; the sample maps those fields from value items.',
123
+ },
124
+ unsupported: ['list properties outside Id, Title, and ItemCount', 'query shapes other than the documented projection/filter/order'],
125
+ }],
126
+ client: {
127
+ interface: 'SPHttpClient', methods: ['get', 'post'], localOnly: true,
128
+ capturedReplay: {
129
+ source: 'consumer .spfx-workbench/captures/tenant-live.json or tenant.har',
130
+ methods: ['GET', 'POST'],
131
+ match: 'SharePoint REST path, sorted query pairs, and canonical JSON POST body; tenant host/site prefix ignored',
132
+ readOnlyPostAllowlist: CAPTURED_READ_POST_ROUTES.map(({ description }) => description),
133
+ fallback: [MOCK_API_PATH, MOCK_WEB_API_PATH, MOCK_LISTS_API_PATH],
134
+ cache: 'Vite process memory; re-indexed when capture file metadata changes',
135
+ },
136
+ version: '@microsoft/sp-http-base 1.24.1',
137
+ interfaceSource: 'https://registry.npmjs.org/@microsoft/sp-http-base/-/sp-http-base-1.24.1.tgz',
138
+ interfaceDeclaration: 'lib-dts/spHttpClient/SPHttpClient.d.ts',
139
+ methodSignatures: [
140
+ 'get(url: string, configuration: SPHttpClientConfiguration, options?: ISPHttpClientOptions): Promise<SPHttpClientResponse>',
141
+ 'post(url: string, configuration: SPHttpClientConfiguration, options: ISPHttpClientOptions): Promise<SPHttpClientResponse>',
142
+ ],
143
+ configurationDeclarations: [
144
+ 'lib-dts/spHttpClient/SPHttpClientConfiguration.d.ts',
145
+ 'lib-dts/spHttpClient/SPHttpClientCommonConfiguration.d.ts',
146
+ ],
147
+ configuration: 'requires an object; documented SPHttpClient flags are accepted but do not alter local replay',
148
+ options: 'GET ISPHttpClientOptions are unsupported; captured read-only POST replay requires a string JSON object body, accepts but ignores headers, and allows only the documented capture-derived route list',
149
+ },
150
+ context: {
151
+ interface: 'WebPartContext',
152
+ version: '@microsoft/sp-webpart-base 1.24.1',
153
+ compatibility: 'Declaration coverage is verified against 1.24.1 only; this does not establish WebPartContext compatibility for later SPFx releases.',
154
+ source: 'https://registry.npmjs.org/@microsoft/sp-webpart-base/-/sp-webpart-base-1.24.1.tgz',
155
+ dependencySources: [
156
+ 'https://registry.npmjs.org/@microsoft/sp-component-base/-/sp-component-base-1.24.1.tgz',
157
+ 'https://registry.npmjs.org/@microsoft/sp-page-context/-/sp-page-context-1.24.1.tgz',
158
+ ],
159
+ declarations: [
160
+ 'lib-dts/core/WebPartContext.d.ts',
161
+ 'lib-dts/core/BaseWebPartContext.d.ts',
162
+ '@microsoft/sp-component-base 1.24.1: lib-dts/RenderableComponentContext.d.ts',
163
+ '@microsoft/sp-component-base 1.24.1: lib-dts/BaseComponentContext.d.ts',
164
+ '@microsoft/sp-page-context 1.24.1: lib-dts/PageContext.d.ts',
165
+ '@microsoft/sp-page-context 1.24.1: lib-dts/SPWeb.d.ts',
166
+ '@microsoft/sp-page-context 1.24.1: lib-dts/SPSite.d.ts',
167
+ '@microsoft/sp-page-context 1.24.1: lib-dts/SPUser.d.ts',
168
+ ],
169
+ supported: [
170
+ 'instanceId', 'domElement', 'manifest', 'displayMode (Edit only)',
171
+ 'isServedFromLocalhost (SharePoint simulator)', 'sdks.microsoftTeams (unset in SharePoint simulator)',
172
+ 'pageContext.web.title', 'pageContext.web.absoluteUrl', 'pageContext.web.serverRelativeUrl',
173
+ 'pageContext.site.absoluteUrl', 'pageContext.site.serverRelativeUrl',
174
+ 'pageContext.user.displayName', 'pageContext.user.loginName',
175
+ 'spHttpClient.get', 'spHttpClient.post for captured read-only API routes only',
176
+ ],
177
+ lifecycle: {
178
+ source: 'https://registry.npmjs.org/@microsoft/sp-webpart-base/-/sp-webpart-base-1.24.1.tgz',
179
+ declaration: 'lib-dts/core/BaseClientSideWebPart.d.ts',
180
+ invoked: ['onInit', 'render', 'onAfterResize', 'onDispose'],
181
+ unsupported: ['onDisplayModeChanged', 'property pane hooks', 'SharePoint service scope and internal initialize/dispose pipeline'],
182
+ },
183
+ unsupported: 'Other WebPartContext and inherited context properties, property pane/display mode host behavior, serviceScope clients, aadHttpClientFactory, aadTokenProviderFactory, msGraphClientFactory, Teams SDK APIs, httpClient, dynamicDataProvider, and dynamicDataSourceManager.',
184
+ },
185
+ method: 'GET',
186
+ captureFormat: FORMAT,
187
+ fields: FIELDS,
188
+ queryOptions: QUERY_OPTIONS,
189
+ response: { status: 200, collection: 'value', maxItems: MAX_ITEMS },
190
+ limits: { Id: { type: 'Edm.Int32', min: 0, max: MAX_ID } },
191
+ top: { min: 1, max: MAX_TOP, default: DEFAULT_TOP },
192
+ source: {
193
+ version: 'SPFx 1.24.1 tutorial',
194
+ url: 'https://learn.microsoft.com/en-us/sharepoint/dev/spfx/copilot/get-started/connect-to-sharepoint-data#show-the-items-in-a-list',
195
+ typeSource: 'https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest',
196
+ basis: 'The SPFx example selects Id, Title, FileLeafRef, and Modified; REST docs represent Id as Edm.Int32 and Modified as Edm.DateTime. Local models are not SDK declarations.',
197
+ },
198
+ unsupported: [
199
+ 'methods other than GET and captured read-only API POST routes',
200
+ 'AAD, Microsoft Graph, Teams, and other service-scope SDK clients',
201
+ 'uncaptured routes outside the three deterministic synthetic fallbacks',
202
+ 'query options outside a route\'s declared allowlist',
203
+ 'list-item fields outside the four-field allowlist',
204
+ 'GET ISPHttpClientOptions and POST options other than a string body and optional ignored headers',
205
+ 'SPHttpClient configuration transport flags and their header/credential behavior',
206
+ 'tenant authentication, forwarding, and writes',
207
+ ],
208
+ });
209
+
210
+ export function diffSyntheticCapture(input) {
211
+ const items = Array.isArray(input?.response?.body?.value)
212
+ ? input.response.body.value
213
+ : Array.isArray(input?.response?.body?.d?.results) ? input.response.body.d.results : [];
214
+ const fieldCounts = new Map(FIELDS.map((field) => [field, 0]));
215
+ let strippedFieldCount = 0;
216
+ for (const item of items) {
217
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
218
+ for (const field of Object.keys(item)) {
219
+ if (fieldCounts.has(field)) fieldCounts.set(field, fieldCounts.get(field) + 1);
220
+ else strippedFieldCount += 1;
221
+ }
222
+ }
223
+ return {
224
+ contract: FORMAT,
225
+ fields: FIELDS.map((name) => ({ name, retained: true, sourceOccurrences: fieldCounts.get(name) })),
226
+ strippedFieldOccurrences: strippedFieldCount,
227
+ requestHeadersIgnored: Boolean(input?.request?.headers),
228
+ };
229
+ }
230
+
231
+ function requireString(value, name, maxLength) {
232
+ if (typeof value !== 'string' || value.length > maxLength) {
233
+ throw new Error(`${name} must be a string no longer than ${maxLength} characters.`);
234
+ }
235
+ return value;
236
+ }
237
+
238
+ function isIsoTimestamp(value) {
239
+ const match = /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:0\d|1\d|2[0-3]):[0-5]\d)$/.exec(value);
240
+ if (!match || !Number.isFinite(Date.parse(value))) return false;
241
+ const [, year, month, day] = match.map(Number);
242
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
243
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
244
+ return Number(month) >= 1 && Number(month) <= 12 && Number(day) >= 1 && Number(day) <= daysInMonth[Number(month) - 1];
245
+ }
246
+
247
+ function listItems(body) {
248
+ const items = Array.isArray(body?.value) ? body.value : body?.d?.results;
249
+ if (!Array.isArray(items) || items.length > MAX_ITEMS) {
250
+ throw new Error(`Expected a SharePoint list response with at most ${MAX_ITEMS} items.`);
251
+ }
252
+
253
+ return items.map((item, index) => {
254
+ if (!item || !Number.isInteger(item.Id) || item.Id < 0 || item.Id > MAX_ID) {
255
+ throw new Error(`Item ${index + 1} Id must be a non-negative Edm.Int32 JSON integer.`);
256
+ }
257
+ const title = requireString(item.Title ?? '', `Item ${index + 1} Title`, 256);
258
+ const fileName = requireString(item.FileLeafRef ?? '', `Item ${index + 1} FileLeafRef`, 255);
259
+ const modified = requireString(item.Modified, `Item ${index + 1} Modified`, 40);
260
+ if (!fileName || !isIsoTimestamp(modified)) {
261
+ throw new Error(`Item ${index + 1} must have a file name and ISO 8601 Modified timestamp with a timezone.`);
262
+ }
263
+ return { Id: item.Id, Title: title, FileLeafRef: fileName, Modified: modified };
264
+ });
265
+ }
266
+
267
+ function queryFor(input, fallback = {}) {
268
+ let query = input.query ?? {};
269
+ if (input.url || input.path) {
270
+ const url = new URL(input.url ?? input.path, 'https://local.invalid');
271
+ const keys = [...url.searchParams.keys()];
272
+ if (new Set(keys).size !== keys.length) throw new Error('Duplicate query options are not supported.');
273
+ const urlQuery = Object.fromEntries(url.searchParams.entries());
274
+ query = { ...query, ...urlQuery };
275
+ }
276
+ if (Object.keys(query).some((key) => !QUERY_OPTIONS.includes(key))) {
277
+ throw new Error('Only $select and $top query options are supported.');
278
+ }
279
+ const fields = String(query.$select ?? fallback.$select ?? FIELDS.join(',')).split(',').map((field) => field.trim());
280
+ if (!fields.length || fields.some((field) => !FIELD_SET.has(field))) {
281
+ throw new Error('Only Id, Title, FileLeafRef, and Modified may be captured.');
282
+ }
283
+ const top = Number(query.$top ?? fallback.$top ?? DEFAULT_TOP);
284
+ if (!Number.isInteger(top) || top < 1 || top > MAX_TOP) throw new Error(`$top must be between 1 and ${MAX_TOP}.`);
285
+ return { $select: [...new Set(fields)].join(','), $top: String(top) };
286
+ }
287
+
288
+ export function normalizeSyntheticCapture(input) {
289
+ if (input?.source !== 'synthetic') {
290
+ throw new Error('Only explicitly synthetic data can be saved for replay.');
291
+ }
292
+
293
+ const request = input.request ?? {};
294
+ const method = String(request.method ?? 'GET').toUpperCase();
295
+ if (method !== 'GET') throw new Error('Only read-only GET captures are supported.');
296
+
297
+ if (request.route && request.route !== ROUTE) throw new Error('Unsupported SharePoint mock route.');
298
+ if (request.url || request.path) {
299
+ let url;
300
+ try { url = new URL(request.url ?? request.path, 'https://local.invalid'); }
301
+ catch { throw new Error('Capture request URL is invalid.'); }
302
+ if (!isSupportedListItemsPath(url.pathname)) {
303
+ throw new Error('Only SharePoint list item collection requests are supported.');
304
+ }
305
+ const allowed = new Set(FIELDS);
306
+ const select = url.searchParams.get('$select');
307
+ if (select && select.split(',').some((field) => !allowed.has(field.trim()))) {
308
+ throw new Error('The request selects fields outside the safe allowlist.');
309
+ }
310
+ }
311
+
312
+ const response = input.response ?? {};
313
+ const status = Number(response.status ?? 200);
314
+ if (status !== 200) throw new Error('Only successful 200 responses can be replayed.');
315
+
316
+ return {
317
+ format: FORMAT,
318
+ source: 'synthetic',
319
+ request: { method: 'GET', route: ROUTE, query: queryFor(request) },
320
+ response: { status, body: { value: listItems(response.body) } },
321
+ };
322
+ }
323
+
324
+ export function validateReplayCapture(input) {
325
+ if (input?.format !== FORMAT) throw new Error(`Expected ${FORMAT}.`);
326
+ return normalizeSyntheticCapture(input);
327
+ }
328
+
329
+ export function validateListItemsQuery(searchParams, fallback = {}) {
330
+ const keys = [...searchParams.keys()];
331
+ if (new Set(keys).size !== keys.length) throw new Error('Duplicate query options are not supported.');
332
+ return queryFor({ query: Object.fromEntries(searchParams.entries()) }, fallback);
333
+ }
334
+
335
+ export function validateWebMetadataQuery(searchParams) {
336
+ const keys = [...searchParams.keys()];
337
+ if (new Set(keys).size !== keys.length) throw new Error('Duplicate query options are not supported.');
338
+ if (keys.some((key) => key !== '$select')) throw new Error('Only the $select=Title query is supported for the web metadata route.');
339
+ if ((searchParams.get('$select') ?? 'Title').trim() !== 'Title') throw new Error('Only the Title field is supported for the web metadata route.');
340
+ return { $select: 'Title' };
341
+ }
342
+
343
+ export function replayWebMetadata(searchParams = new URLSearchParams()) {
344
+ validateWebMetadataQuery(searchParams);
345
+ return { Title: MOCK_WEB_TITLE };
346
+ }
347
+
348
+ export function validateSharePointListsQuery(searchParams) {
349
+ const keys = [...searchParams.keys()];
350
+ if (new Set(keys).size !== keys.length) throw new Error('Duplicate query options are not supported.');
351
+ const required = {
352
+ '$select': 'Id,Title,ItemCount',
353
+ '$filter': 'Hidden eq false',
354
+ '$orderby': 'Title',
355
+ };
356
+ if (keys.length !== Object.keys(required).length || Object.entries(required).some(([key, value]) => searchParams.get(key) !== value)) {
357
+ throw new Error('Only the documented list metadata query ($select=Id,Title,ItemCount&$filter=Hidden eq false&$orderby=Title) is supported.');
358
+ }
359
+ return required;
360
+ }
361
+
362
+ export function replaySharePointLists(searchParams) {
363
+ validateSharePointListsQuery(searchParams);
364
+ return { value: MOCK_SHAREPOINT_LISTS.map((list) => ({ ...list })) };
365
+ }
366
+
367
+ export function replayListItems(input, searchParams = new URLSearchParams()) {
368
+ const capture = validateReplayCapture(input);
369
+ const query = validateListItemsQuery(searchParams, capture.request.query);
370
+ const fields = query.$select.split(',');
371
+ const value = capture.response.body.value.slice(0, Number(query.$top)).map((item) =>
372
+ Object.fromEntries(fields.map((field) => [field, item[field]])),
373
+ );
374
+ return { value };
375
+ }
@@ -0,0 +1,123 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { chromium } from 'playwright-core';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { readdir } from 'node:fs/promises';
5
+ import { resolveChromiumExecutable } from './resolve-chromium.mjs';
6
+
7
+ const args = process.argv.slice(2);
8
+ const valueAfter = (flag) => {
9
+ const index = args.indexOf(flag);
10
+ return index < 0 ? undefined : args[index + 1];
11
+ };
12
+ const valuesAfter = (flag) => args.flatMap((value, index) => value === flag && args[index + 1] && !args[index + 1].startsWith('--') ? [args[index + 1]] : []);
13
+ const harPath = valueAfter('--capture');
14
+ const fallbackCapturePaths = valuesAfter('--fallback-capture').map((path) => resolve(path));
15
+ const usage = 'Usage: spfx-workbench-replay --capture <tenant.har> [--fallback-capture <cached.har>]... [--width <px>] [--height <px>] [--headed] [--once]';
16
+ const safeError = (error) => String(error?.errorText ?? error?.message ?? error).replace(/(?:https?|wss?):\/\/[^\s"'<>]+/g, (value) => {
17
+ try { const url = new URL(value); return `${url.origin}${url.pathname}`; } catch { return '[URL]'; }
18
+ });
19
+
20
+ if (args.includes('--help') || args.includes('-h')) {
21
+ process.stdout.write(`${usage}\n`);
22
+ process.exit(0);
23
+ }
24
+
25
+ if (!harPath) {
26
+ process.stderr.write(`${usage}\n`);
27
+ process.exitCode = 2;
28
+ } else {
29
+ let browser;
30
+ let context;
31
+ try {
32
+ const capturePath = resolve(harPath);
33
+ const har = JSON.parse(await readFile(capturePath, 'utf8'));
34
+ const captureDirectory = dirname(capturePath);
35
+ const archiveFiles = await readdir(captureDirectory, { withFileTypes: true });
36
+ const automaticArchivePaths = archiveFiles
37
+ .filter((entry) => entry.isFile() && /^tenant-archive-\d{8}T?\d{6,9}Z?-[a-f0-9]{12}\.har$/i.test(entry.name))
38
+ .map((entry) => resolve(captureDirectory, entry.name))
39
+ .sort();
40
+ const explicitFallbacks = new Set(fallbackCapturePaths);
41
+ const localFallbackPaths = [
42
+ ...automaticArchivePaths.filter((path) => !explicitFallbacks.has(path)),
43
+ ...fallbackCapturePaths,
44
+ ];
45
+ const firstDocument = har.log?.entries?.find((entry) => entry.request?.method === 'GET' && /text\/html/i.test(entry.response?.content?.mimeType ?? ''));
46
+ const targetUrl = firstDocument?.request?.url;
47
+ if (!targetUrl) throw new Error('HAR has no page URL to replay.');
48
+ const target = new URL(targetUrl);
49
+ const targetSitePath = target.pathname.match(/^\/(?:sites|teams|personal)\/[^/]+/i)?.[0] ?? '';
50
+ const contextInfoPath = `${targetSitePath}/_api/contextinfo`.toLowerCase();
51
+ const isTargetContextInfo = (url) => url.origin === target.origin
52
+ && url.pathname.replace(/\/+$/, '').toLowerCase() === contextInfoPath;
53
+ const hasCapturedContextInfo = har.log.entries.some((entry) => {
54
+ if (entry.request?.method !== 'POST' || (entry.response?.status ?? 0) < 200 || (entry.response?.status ?? 0) >= 300) return false;
55
+ if (!entry.response?.content?.text) return false;
56
+ try { return isTargetContextInfo(new URL(entry.request.url)); } catch { return false; }
57
+ });
58
+
59
+ const width = Number(valueAfter('--width') ?? 1366);
60
+ const height = Number(valueAfter('--height') ?? 900);
61
+ if (!Number.isInteger(width) || width < 240 || width > 3840 || !Number.isInteger(height) || height < 240 || height > 2160) {
62
+ throw new Error('Viewport must be between 240 and 3840 pixels wide and 240 and 2160 pixels high.');
63
+ }
64
+ browser = await chromium.launch({ headless: !args.includes('--headed'), executablePath: await resolveChromiumExecutable() });
65
+ context = await browser.newContext({ viewport: { width, height }, serviceWorkers: 'block' });
66
+ await context.route('**/*', (route) => route.abort());
67
+ await context.route('**/*', (route) => {
68
+ const requestUrl = new URL(route.request().url());
69
+ if (!hasCapturedContextInfo && route.request().method() === 'POST' && isTargetContextInfo(requestUrl)) {
70
+ return route.fulfill({
71
+ status: 200,
72
+ contentType: 'application/json',
73
+ body: JSON.stringify({ d: { GetContextWebInformation: { FormDigestValue: 'offline-replay', FormDigestTimeoutSeconds: 1800 } } }),
74
+ });
75
+ }
76
+ return route.fallback();
77
+ });
78
+ for (const fallbackPath of localFallbackPaths) {
79
+ await context.routeFromHAR(fallbackPath, { notFound: 'fallback' });
80
+ }
81
+ await context.routeFromHAR(capturePath, { notFound: 'fallback' });
82
+ const page = await context.newPage();
83
+ const statusCounts = {};
84
+ const failedRequests = [];
85
+ const pageErrors = [];
86
+ context.on('response', (response) => {
87
+ const key = `${response.request().resourceType()}:${response.status()}`;
88
+ statusCounts[key] = (statusCounts[key] ?? 0) + 1;
89
+ });
90
+ page.on('requestfailed', (request) => {
91
+ let path = '[invalid URL]';
92
+ let queryOptions = [];
93
+ try {
94
+ const url = new URL(request.url());
95
+ path = `${url.origin}${url.pathname}`;
96
+ queryOptions = [...new Set(url.searchParams.keys())].sort();
97
+ } catch {}
98
+ failedRequests.push({ method: request.method(), resourceType: request.resourceType(), path, queryOptions, error: safeError(request.failure() ?? 'request failed') });
99
+ });
100
+ page.on('pageerror', (error) => pageErrors.push(safeError(error)));
101
+ await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 45_000 });
102
+ if (args.includes('--once')) await page.waitForTimeout(4000);
103
+ else await new Promise((done) => {
104
+ process.once('SIGINT', done);
105
+ process.once('SIGTERM', done);
106
+ });
107
+ const pageState = await page.evaluate(() => ({
108
+ documentWidth: document.documentElement.scrollWidth,
109
+ viewportWidth: innerWidth,
110
+ canvasSections: document.querySelectorAll('[class*="CanvasSection"]').length,
111
+ webPartControls: document.querySelectorAll('[class*="ControlZone"]').length,
112
+ capturedContextInfo: document.body.dataset.digestSource === 'captured',
113
+ }));
114
+ process.stdout.write(JSON.stringify({ result: 'replayed', source: 'local HAR only', fallbackCaptureCount: localFallbackPaths.length, automaticArchiveCount: automaticArchivePaths.length, viewport: { width, height }, statusCounts, failedRequests, pageErrors, pageState }) + '\n');
115
+ } catch (error) {
116
+ process.stderr.write(`Replay failed: ${safeError(error)}\n`);
117
+ process.stderr.write('Replay failed. The HAR may not contain the page or one of its required requests.\n');
118
+ process.exitCode = 1;
119
+ } finally {
120
+ await context?.close().catch(() => {});
121
+ await browser?.close().catch(() => {});
122
+ }
123
+ }
@@ -0,0 +1,22 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join } from 'node:path';
5
+ import { chromium } from 'playwright-core';
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ export async function resolveChromiumExecutable() {
10
+ const executablePath = chromium.executablePath();
11
+ try { await access(executablePath); return executablePath; } catch {}
12
+
13
+ const packagePath = require.resolve('playwright-core/package.json');
14
+ const cliPath = join(dirname(packagePath), 'cli.js');
15
+ const install = spawnSync(process.execPath, [cliPath, 'install', 'chromium'], { stdio: 'inherit' });
16
+ if (install.error) throw new Error(`Could not install Playwright Chromium: ${install.error.message}`);
17
+ if (install.status !== 0) throw new Error('Could not install Playwright Chromium. Run: npx playwright-core install chromium');
18
+ try { await access(executablePath); return executablePath; }
19
+ catch {
20
+ throw new Error('Playwright Chromium was installed but its executable is unavailable. Check the Playwright browser cache for this operating system.');
21
+ }
22
+ }
@@ -0,0 +1,70 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+
4
+ export function resolveServeTarget(config, name = 'default', tenantDomain = process.env.SPFX_SERVE_TENANT_DOMAIN) {
5
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
6
+ throw new Error('serve.json must contain a JSON object.');
7
+ }
8
+
9
+ const initialPage = config.initialPage;
10
+ const selected = typeof initialPage === 'string' && initialPage.trim()
11
+ ? { value: initialPage, source: 'initialPage', configuration: null }
12
+ : { value: config.serveConfigurations?.[name]?.pageUrl, source: 'pageUrl', configuration: name };
13
+ if (typeof selected.value !== 'string' || !selected.value.trim()) {
14
+ throw new Error(`No initialPage or pageUrl found for serve configuration "${name}".`);
15
+ }
16
+
17
+ let target = selected.value;
18
+ if (target.includes('{tenantDomain}')) {
19
+ const domain = tenantDomain?.trim();
20
+ if (!domain) throw new Error(`${selected.source} uses {tenantDomain}; set SPFX_SERVE_TENANT_DOMAIN to resolve it.`);
21
+ let domainUrl;
22
+ try { domainUrl = new URL(`https://${domain}`); } catch {}
23
+ if (domain.includes('://') || /[?#\s]/.test(domain) || domain.split('/')[0].includes('@') || !domainUrl?.hostname || domainUrl.username || domainUrl.password) {
24
+ throw new Error('SPFX_SERVE_TENANT_DOMAIN must be a hostname or site path without a scheme, credentials, query, or fragment.');
25
+ }
26
+ target = target.replaceAll('{tenantDomain}', domain);
27
+ }
28
+
29
+ let url;
30
+ try { url = new URL(target); }
31
+ catch { throw new Error(`${selected.source} must be an absolute HTTP(S) URL.`); }
32
+ if (!['http:', 'https:'].includes(url.protocol) || !url.hostname || url.username || url.password) {
33
+ throw new Error(`${selected.source} must be an absolute HTTP(S) URL without embedded credentials.`);
34
+ }
35
+ return { url: target, source: selected.source, configuration: selected.configuration };
36
+ }
37
+
38
+ const args = process.argv.slice(2);
39
+ function parseArgs() {
40
+ const parsed = { configPath: 'config/serve.json', configuration: 'default', json: false, help: false };
41
+ for (let index = 0; index < args.length; index += 1) {
42
+ const arg = args[index];
43
+ if (arg === '--help' || arg === '-h') parsed.help = true;
44
+ else if (arg === '--json') parsed.json = true;
45
+ else if (arg === '--config' || arg === '--serve-config') {
46
+ const value = args[++index];
47
+ if (!value || value.startsWith('--')) throw new Error(`${arg} requires a value.`);
48
+ if (arg === '--config') parsed.configPath = value;
49
+ else parsed.configuration = value;
50
+ } else throw new Error(`Unsupported argument: ${arg}`);
51
+ }
52
+ return parsed;
53
+ }
54
+
55
+ try {
56
+ const options = parseArgs();
57
+ if (options.help) {
58
+ process.stdout.write('Usage: spfx-workbench-heft-target [--serve-config <name>] [--config <serve.json>] [--json]\nPrints the configured Heft page target without opening it.\n');
59
+ process.exit(0);
60
+ }
61
+ const configPath = resolve(options.configPath);
62
+ const config = JSON.parse(await readFile(configPath, 'utf8'));
63
+ const result = resolveServeTarget(config, options.configuration);
64
+ process.stdout.write(options.json
65
+ ? `${JSON.stringify({ schema: 'spfx-workbench-heft-target/v1', ...result })}\n`
66
+ : `${result.url}\n`);
67
+ } catch (error) {
68
+ process.stderr.write(`Could not resolve SharePoint serve target: ${error.message}\n`);
69
+ process.exitCode = 1;
70
+ }
@@ -0,0 +1,19 @@
1
+ const SOURCE = 'https://learn.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-development-environment';
2
+ const EXPECTED = 'SPFx 1.24.1 supports Node.js 22.14.0 or later within 22.x, 24.x, and 26.x';
3
+
4
+ /** Checks only the SPFx release for which the current Microsoft compatibility guidance is explicit. */
5
+ export function checkSPFxNodeRuntime(spfxVersion, nodeVersion) {
6
+ const result = { name: 'spfx-node-runtime', spfxVersion: spfxVersion ?? null, nodeVersion: nodeVersion ?? null, expected: EXPECTED, source: SOURCE };
7
+ if (spfxVersion !== '1.24.1') {
8
+ return { ...result, status: 'unknown', reason: 'Current runtime guidance is recorded for SPFx 1.24.1; other releases need their compatibility entry.' };
9
+ }
10
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(nodeVersion ?? '');
11
+ if (!match) return { ...result, status: 'unknown', reason: 'The active Node.js version could not be parsed.' };
12
+ const [major, minor] = match.slice(1).map(Number);
13
+ const supported = (major === 22 && minor >= 14) || major === 24 || major === 26;
14
+ return {
15
+ ...result,
16
+ status: supported ? 'supported' : 'unsupported',
17
+ reason: supported ? 'The active Node.js major/minor is listed by Microsoft for SPFx 1.24.1.' : 'The active Node.js major/minor is not listed by Microsoft for SPFx 1.24.1.',
18
+ };
19
+ }