@spfx-fast/spfx-workbench 0.0.0-stage → 0.1.1
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 +77 -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,413 @@
|
|
|
1
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { arch, platform } from 'node:os';
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
import { createServer } from 'node:net';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { dirname, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
10
|
+
const manifest = JSON.parse(await readFile(resolve(packageRoot, 'package.json'), 'utf8'));
|
|
11
|
+
const temp = await mkdtemp(resolve(tmpdir(), 'spfx-tarball-check-'));
|
|
12
|
+
const run = (command, args, cwd, env = process.env) => {
|
|
13
|
+
const npmFromNode = command === 'npm' && env.npm_execpath;
|
|
14
|
+
return spawnSync(npmFromNode ? process.execPath : command, npmFromNode ? [env.npm_execpath, ...args] : args, {
|
|
15
|
+
cwd, env, encoding: 'utf8', timeout: 120_000, maxBuffer: 8 * 1024 * 1024,
|
|
16
|
+
...(command === 'npm' && process.platform === 'win32' && !npmFromNode ? { shell: true } : {}),
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
async function freeLoopbackPort() {
|
|
21
|
+
const probe = createServer();
|
|
22
|
+
await new Promise((resolveListen, reject) => {
|
|
23
|
+
probe.once('error', reject);
|
|
24
|
+
probe.listen(0, '127.0.0.1', resolveListen);
|
|
25
|
+
});
|
|
26
|
+
const port = probe.address().port;
|
|
27
|
+
await new Promise((resolveClose) => probe.close(resolveClose));
|
|
28
|
+
return port;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function verifyPackagedPreview(packagePath, binPath) {
|
|
32
|
+
const previewStartedAt = performance.now();
|
|
33
|
+
const sourceDir = resolve(temp, 'src');
|
|
34
|
+
await mkdir(sourceDir, { recursive: true });
|
|
35
|
+
await writeFile(resolve(temp, '.gitignore'), '.spfx-workbench/captures/\n');
|
|
36
|
+
const harUrl = 'https://tenant.synthetic.invalid/sites/other/_api/web?$select=Title';
|
|
37
|
+
const harListDataUrl = "https://tenant.synthetic.invalid/sites/other/_api/web/GetList(@listUrl)/RenderListDataAsStream?@listUrl='%2Fsites%2Fother%2FShared%20Documents'";
|
|
38
|
+
const harListDataBody = '{"parameters":{"RenderOptions":136967,"ViewXml":"<View />"}}';
|
|
39
|
+
await mkdir(resolve(temp, '.spfx-workbench/captures'), { recursive: true });
|
|
40
|
+
await writeFile(resolve(temp, '.spfx-workbench/captures/tenant.har'), JSON.stringify({ log: { entries: [{
|
|
41
|
+
request: { method: 'GET', url: harUrl },
|
|
42
|
+
response: { status: 202, headers: [{ name: 'X-Tarball-Capture', value: 'replayed' }, { name: 'Set-Cookie', value: 'private=sentinel' }], content: { mimeType: 'application/json', text: '{"Title":"Packaged captured response","extra":"retained"}' } },
|
|
43
|
+
}, {
|
|
44
|
+
request: { method: 'POST', url: harListDataUrl, headers: [], queryString: [], postData: { mimeType: 'application/json', text: harListDataBody } },
|
|
45
|
+
response: { status: 206, headers: [{ name: 'Content-Type', value: 'application/json' }], content: { mimeType: 'application/json', text: '{"ListData":{"Row":[{"ID":"9"}]}}' } },
|
|
46
|
+
}] } }));
|
|
47
|
+
await writeFile(resolve(sourceDir, 'TarballComponent.jsx'), 'export default function TarballComponent({ title }) { return <div>{title}</div>; }\n');
|
|
48
|
+
await writeFile(resolve(temp, 'preview-props.json'), JSON.stringify({ title: 'Tarball Preview Prop' }));
|
|
49
|
+
const port = await freeLoopbackPort();
|
|
50
|
+
const server = spawn(process.execPath, [
|
|
51
|
+
resolve(packagePath, binPath), '--component', 'src/TarballComponent.jsx', '--props-file', 'preview-props.json', '--port', String(port),
|
|
52
|
+
], { cwd: temp, stdio: 'ignore' });
|
|
53
|
+
try {
|
|
54
|
+
const base = `http://127.0.0.1:${port}`;
|
|
55
|
+
let ready = false;
|
|
56
|
+
const deadline = Date.now() + 10_000;
|
|
57
|
+
while (Date.now() < deadline && server.exitCode === null) {
|
|
58
|
+
try {
|
|
59
|
+
const response = await fetch(`${base}/`);
|
|
60
|
+
if (response.ok) { ready = true; break; }
|
|
61
|
+
} catch {}
|
|
62
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
|
63
|
+
}
|
|
64
|
+
if (!ready) throw new Error('Packaged component preview did not become ready.');
|
|
65
|
+
const previewReadyMs = performance.now() - previewStartedAt;
|
|
66
|
+
|
|
67
|
+
const entry = await (await fetch(`${base}/src/main.jsx`)).text();
|
|
68
|
+
const virtualPath = entry.match(/from "([^"]*virtual[^"]*)"/)?.[1];
|
|
69
|
+
if (!virtualPath) throw new Error('Packaged preview entry did not load the consumer wrapper.');
|
|
70
|
+
const wrapper = await fetch(new URL(virtualPath, base));
|
|
71
|
+
const wrapperSource = await wrapper.text();
|
|
72
|
+
if (!wrapper.ok || !wrapperSource.includes('Tarball Preview Prop') || !wrapperSource.includes('createSimulatorContext')) {
|
|
73
|
+
throw new Error('Packaged consumer props/context wrapper did not load.');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const replay = await fetch(`${base}/__spfx_workbench/api/library-items?$top=1`);
|
|
77
|
+
const replayBody = await replay.json();
|
|
78
|
+
if (!replay.ok || replay.headers.get('X-SPFx-Workbench-Data') !== 'committed-synthetic-fixture' || replayBody.value?.[0]?.Id !== 101) {
|
|
79
|
+
throw new Error('Packaged synthetic replay endpoint did not return the expected fixture.');
|
|
80
|
+
}
|
|
81
|
+
const captured = await fetch(`${base}/__spfx_workbench/api/captured`, {
|
|
82
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
83
|
+
body: JSON.stringify({ url: 'https://contoso.sharepoint.test/sites/workbench/_api/web?$select=Title', sessionId: '00000000-0000-4000-8000-000000000001' }),
|
|
84
|
+
});
|
|
85
|
+
if (captured.status !== 202 || captured.headers.get('X-Tarball-Capture') !== 'replayed'
|
|
86
|
+
|| captured.headers.get('set-cookie') !== null
|
|
87
|
+
|| JSON.stringify(await captured.json()) !== '{"Title":"Packaged captured response","extra":"retained"}') {
|
|
88
|
+
throw new Error('Packaged Vite middleware did not replay the consumer HAR response faithfully.');
|
|
89
|
+
}
|
|
90
|
+
const capturedListData = await fetch(`${base}/__spfx_workbench/api/captured`, {
|
|
91
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
92
|
+
body: JSON.stringify({ url: harListDataUrl, sessionId: '00000000-0000-4000-8000-000000000001', method: 'POST', requestBody: '{ "parameters" : { "ViewXml" : "<View />", "RenderOptions" : 136967 } }' }),
|
|
93
|
+
});
|
|
94
|
+
if (capturedListData.status !== 206 || JSON.stringify(await capturedListData.json()) !== '{"ListData":{"Row":[{"ID":"9"}]}}') {
|
|
95
|
+
throw new Error('Packaged Vite middleware did not match the captured read-only list-render POST by canonical JSON body.');
|
|
96
|
+
}
|
|
97
|
+
return { previewReadyMs, usablePreviewMs: performance.now() - previewStartedAt };
|
|
98
|
+
} finally {
|
|
99
|
+
if (server.exitCode === null) {
|
|
100
|
+
const exited = new Promise((resolveExit) => server.once('exit', resolveExit));
|
|
101
|
+
server.kill('SIGTERM');
|
|
102
|
+
await Promise.race([exited, new Promise((resolveDelay) => setTimeout(resolveDelay, 3000))]);
|
|
103
|
+
if (server.exitCode === null) server.kill('SIGKILL');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function verifyPackagedSPHttpClient(packagePath) {
|
|
109
|
+
const { createSimulatorContext } = await import(pathToFileURL(resolve(packagePath, 'src/simulator-context.mjs')).href);
|
|
110
|
+
const originalFetch = globalThis.fetch;
|
|
111
|
+
const calls = [];
|
|
112
|
+
globalThis.fetch = async (url, options) => {
|
|
113
|
+
calls.push({ url, options });
|
|
114
|
+
const path = new URL(url, 'http://workbench.test').pathname;
|
|
115
|
+
const requestUrl = JSON.parse(options.body).url;
|
|
116
|
+
const body = requestUrl.includes('/_api/web/lists(guid') ? '{"value":[]}'
|
|
117
|
+
: requestUrl.includes('/_api/web/lists?') ? '{"value":[{"Id":"11111111-1111-4111-8111-111111111111","Title":"Workbench Documents","ItemCount":12},{"Id":"22222222-2222-4222-8222-222222222222","Title":"Workbench Media","ItemCount":7}]}'
|
|
118
|
+
: '{"Title":"Workbench site"}';
|
|
119
|
+
return new Response(body, { status: 200, headers: { 'Content-Type': 'application/json', 'X-SPFx-Workbench-HAR-Version': 'synthetic-test' } });
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
const context = createSimulatorContext();
|
|
123
|
+
const response = await context.spHttpClient.get(
|
|
124
|
+
"https://contoso.sharepoint.test/sites/workbench/_api/web/lists(guid'1234')/items?$select=Id&$top=1",
|
|
125
|
+
{ jsonResponse: true, defaultSameOriginCredentials: true },
|
|
126
|
+
);
|
|
127
|
+
const localRequest = new URL(calls[0]?.url, 'http://workbench.test');
|
|
128
|
+
const firstInput = JSON.parse(calls[0]?.options.body);
|
|
129
|
+
if (response.status !== 200 || localRequest.pathname !== '/__spfx_workbench/api/captured' || firstInput.url !== "https://contoso.sharepoint.test/sites/workbench/_api/web/lists(guid'1234')/items?$select=Id&$top=1") {
|
|
130
|
+
throw new Error('Packaged spHttpClient.get did not send its SharePoint REST request to local capture replay.');
|
|
131
|
+
}
|
|
132
|
+
if (calls[0].options.credentials !== 'omit' || calls[0].options.method !== 'POST' || calls[0].options.redirect !== 'error') {
|
|
133
|
+
throw new Error('Packaged spHttpClient.get did not enforce its local read-only request policy.');
|
|
134
|
+
}
|
|
135
|
+
const webResponse = await context.spHttpClient.get(
|
|
136
|
+
'https://contoso.sharepoint.test/sites/workbench/_api/web?$select=Title', {},
|
|
137
|
+
);
|
|
138
|
+
const webRequest = JSON.parse(calls[1]?.options.body).url;
|
|
139
|
+
if (webResponse.status !== 200 || !webRequest.endsWith('/_api/web?$select=Title') || (await webResponse.json()).Title !== 'Workbench site') {
|
|
140
|
+
throw new Error('Packaged spHttpClient.get did not map the web-title read to its deterministic local mock.');
|
|
141
|
+
}
|
|
142
|
+
const listsResponse = await context.spHttpClient.get(
|
|
143
|
+
'https://contoso.sharepoint.test/sites/workbench/_api/web/lists?$select=Id,Title,ItemCount&$filter=Hidden%20eq%20false&$orderby=Title', {},
|
|
144
|
+
);
|
|
145
|
+
const listsRequest = JSON.parse(calls[2]?.options.body).url;
|
|
146
|
+
const lists = await listsResponse.json();
|
|
147
|
+
if (listsResponse.status !== 200 || !listsRequest.includes('/_api/web/lists?') || lists.value?.length !== 2 || lists.value[0].ItemCount !== 12) {
|
|
148
|
+
throw new Error('Packaged spHttpClient.get did not map list metadata to its deterministic local mock.');
|
|
149
|
+
}
|
|
150
|
+
const crossTenant = await context.spHttpClient.get('https://workswithagents.sharepoint.com/sites/spfx-validation-lab/_api/web?$select=Title', {});
|
|
151
|
+
const crossTenantUrl = JSON.parse(calls[3]?.options.body).url;
|
|
152
|
+
if (crossTenant.status !== 200 || crossTenantUrl !== 'https://workswithagents.sharepoint.com/sites/spfx-validation-lab/_api/web?$select=Title'
|
|
153
|
+
|| new URL(calls[3]?.url, 'http://workbench.test').origin !== 'http://workbench.test') {
|
|
154
|
+
throw new Error('Packaged spHttpClient.get did not route a cross-tenant SharePoint URL to local replay.');
|
|
155
|
+
}
|
|
156
|
+
const listDataUrl = "https://contoso.sharepoint.test/sites/workbench/_api/web/GetList(@listUrl)/RenderListDataAsStream?@listUrl='%2Fsites%2Fworkbench%2FShared%20Documents'";
|
|
157
|
+
const listDataBody = '{"parameters":{"RenderOptions":136967,"ViewXml":"<View />"}}';
|
|
158
|
+
const listData = await context.spHttpClient.post(listDataUrl, {}, { body: listDataBody });
|
|
159
|
+
const postInput = JSON.parse(calls[4]?.options.body);
|
|
160
|
+
if (listData.status !== 200 || postInput.method !== 'POST' || postInput.requestBody !== listDataBody
|
|
161
|
+
|| new URL(calls[4]?.url, 'http://workbench.test').origin !== 'http://workbench.test') {
|
|
162
|
+
throw new Error('Packaged spHttpClient.post did not send a captured list-render call to local replay.');
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
await context.spHttpClient.post('https://contoso.sharepoint.test/_api/web/SavePageCoAuth', {}, { body: '{}' });
|
|
166
|
+
throw new Error('Packaged spHttpClient.post accepted a SharePoint write route.');
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (!/only captured read-only API routes/.test(error.message)) throw error;
|
|
169
|
+
}
|
|
170
|
+
if (calls.length !== 5) throw new Error('Packaged simulator made an unexpected request for a rejected write route.');
|
|
171
|
+
} finally {
|
|
172
|
+
globalThis.fetch = originalFetch;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function verifyPackagedDebugLauncher(packagePath, binPath) {
|
|
177
|
+
const heftBin = resolve(temp, 'node_modules/@rushstack/heft/bin/heft.cjs');
|
|
178
|
+
const startedPath = resolve(temp, 'synthetic-heft-started.json');
|
|
179
|
+
const stoppedPath = resolve(temp, 'synthetic-heft-stopped');
|
|
180
|
+
const missingHeftPort = await freeLoopbackPort();
|
|
181
|
+
const missingHeft = run(process.execPath, [
|
|
182
|
+
resolve(packagePath, binPath), '--component', 'src/TarballComponent.jsx', '--port', String(missingHeftPort),
|
|
183
|
+
], temp);
|
|
184
|
+
if (missingHeft.status !== 1 || !missingHeft.stderr.includes('Could not find the consuming project\'s local @rushstack/heft installation')) {
|
|
185
|
+
throw new Error('Packaged debug launcher did not reject a missing local Heft installation.');
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
await fetch(`http://127.0.0.1:${missingHeftPort}/`);
|
|
189
|
+
throw new Error('Packaged debug launcher started a preview before finding Heft.');
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error.message === 'Packaged debug launcher started a preview before finding Heft.') throw error;
|
|
192
|
+
}
|
|
193
|
+
await mkdir(dirname(heftBin), { recursive: true });
|
|
194
|
+
await writeFile(resolve(dirname(heftBin), '..', 'package.json'), JSON.stringify({
|
|
195
|
+
name: '@rushstack/heft', version: '1.0.0', bin: { heft: 'bin/heft.cjs' },
|
|
196
|
+
}));
|
|
197
|
+
await writeFile(heftBin, `const { rename, writeFile } = require('node:fs/promises');\nconst marker = ${JSON.stringify(startedPath)};\n(async () => { await writeFile(marker + '.tmp', JSON.stringify(process.argv.slice(2))); await rename(marker + '.tmp', marker); })().catch((error) => { console.error(error); process.exitCode = 1; });\nif (process.platform !== 'win32') process.once('SIGTERM', async () => { await writeFile(${JSON.stringify(stoppedPath)}, 'stopped'); process.exit(0); });\nsetInterval(() => {}, 1000);\n`);
|
|
198
|
+
const port = await freeLoopbackPort();
|
|
199
|
+
const launcher = spawn(process.execPath, [
|
|
200
|
+
resolve(packagePath, binPath), '--component', 'src/TarballComponent.jsx', '--port', String(port), '--', '--serve-config=default',
|
|
201
|
+
], { cwd: temp, stdio: 'ignore' });
|
|
202
|
+
const waitForPath = async (path, timeoutMs = 10000) => {
|
|
203
|
+
const deadline = Date.now() + timeoutMs;
|
|
204
|
+
while (Date.now() < deadline && launcher.exitCode === null) {
|
|
205
|
+
try { return await readFile(path, 'utf8'); } catch {}
|
|
206
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
|
207
|
+
}
|
|
208
|
+
throw new Error('Packaged debug launcher did not complete its synthetic Heft lifecycle.');
|
|
209
|
+
};
|
|
210
|
+
try {
|
|
211
|
+
const args = JSON.parse(await waitForPath(startedPath));
|
|
212
|
+
const response = await fetch(`http://127.0.0.1:${port}/`);
|
|
213
|
+
if (!response.ok || JSON.stringify(args) !== JSON.stringify(['start', '--serve-config=default'])) {
|
|
214
|
+
throw new Error('Packaged debug launcher did not start the local preview and forward Heft options.');
|
|
215
|
+
}
|
|
216
|
+
} finally {
|
|
217
|
+
if (launcher.exitCode === null) {
|
|
218
|
+
const exited = new Promise((resolveExit) => launcher.once('exit', resolveExit));
|
|
219
|
+
launcher.kill('SIGTERM');
|
|
220
|
+
await Promise.race([exited, new Promise((resolveDelay) => setTimeout(resolveDelay, 5000))]);
|
|
221
|
+
if (launcher.exitCode === null) launcher.kill('SIGKILL');
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (process.platform !== 'win32') {
|
|
225
|
+
try {
|
|
226
|
+
await readFile(stoppedPath, 'utf8');
|
|
227
|
+
} catch {
|
|
228
|
+
throw new Error('Packaged debug launcher did not stop its local Heft child.');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function verifyPackagedDoctor(packagePath, binPath) {
|
|
234
|
+
for (const [name, version] of [
|
|
235
|
+
['@microsoft/sp-core-library', '1.24.1'],
|
|
236
|
+
['@microsoft/sp-webpart-base', '1.24.1'],
|
|
237
|
+
['react', '18.3.1'],
|
|
238
|
+
['react-dom', '18.3.1'],
|
|
239
|
+
]) {
|
|
240
|
+
const directory = resolve(temp, 'node_modules', ...name.split('/'));
|
|
241
|
+
await mkdir(directory, { recursive: true });
|
|
242
|
+
await writeFile(resolve(directory, 'package.json'), JSON.stringify({ name, version }));
|
|
243
|
+
}
|
|
244
|
+
const diagnostic = run(process.execPath, [resolve(packagePath, binPath)], temp);
|
|
245
|
+
if (diagnostic.status !== 0) throw new Error('Packaged doctor failed against a synthetic supported SPFx consumer.');
|
|
246
|
+
const result = JSON.parse(diagnostic.stdout);
|
|
247
|
+
if (result.summary !== 'supported'
|
|
248
|
+
|| result.checks.find(({ name }) => name === 'spfx-node-runtime')?.status !== 'supported'
|
|
249
|
+
|| result.checks.find(({ name }) => name === 'simulator-context-contract')?.status !== 'supported') {
|
|
250
|
+
throw new Error('Packaged doctor did not report the synthetic SPFx, Node.js, and pinned simulator context contract as supported.');
|
|
251
|
+
}
|
|
252
|
+
const context = result.mockCoverage?.context;
|
|
253
|
+
if (context?.version !== '@microsoft/sp-webpart-base 1.24.1'
|
|
254
|
+
|| !context.declarations?.includes('lib-dts/core/WebPartContext.d.ts')
|
|
255
|
+
|| !context.declarations?.includes('@microsoft/sp-page-context 1.24.1: lib-dts/PageContext.d.ts')
|
|
256
|
+
|| !context.supported?.includes('pageContext.web.title')
|
|
257
|
+
|| !/1\.24\.1 only/.test(context.compatibility ?? '')) {
|
|
258
|
+
throw new Error('Packaged doctor omitted the pinned simulator context coverage or its compatibility boundary.');
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function verifyPackagedHeftTarget(packagePath, binPath) {
|
|
263
|
+
await mkdir(resolve(temp, 'config'), { recursive: true });
|
|
264
|
+
await writeFile(resolve(temp, 'config/serve.json'), JSON.stringify({
|
|
265
|
+
serveConfigurations: { default: { pageUrl: 'https://{tenantDomain}/SitePages/Test.aspx' } },
|
|
266
|
+
}));
|
|
267
|
+
const result = run(process.execPath, [resolve(packagePath, binPath), '--json'], temp, {
|
|
268
|
+
...process.env, SPFX_SERVE_TENANT_DOMAIN: 'tenant.synthetic.invalid/sites/dev',
|
|
269
|
+
});
|
|
270
|
+
if (result.status !== 0) throw new Error('Packaged Heft target command failed on the synthetic tenant placeholder.');
|
|
271
|
+
const target = JSON.parse(result.stdout);
|
|
272
|
+
if (target.source !== 'pageUrl' || target.url !== 'https://tenant.synthetic.invalid/sites/dev/SitePages/Test.aspx') {
|
|
273
|
+
throw new Error('Packaged Heft target command did not resolve SPFX_SERVE_TENANT_DOMAIN.');
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function verifyPackagedCaptureDiff(packagePath, binPath) {
|
|
278
|
+
const entry = (value) => ({
|
|
279
|
+
request: { method: 'GET', url: 'https://tenant.synthetic.invalid/_api/web', queryString: [] },
|
|
280
|
+
response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify({ value }) } },
|
|
281
|
+
});
|
|
282
|
+
await writeFile(resolve(temp, 'diff-before.har'), JSON.stringify({ log: { entries: [entry('before')] } }));
|
|
283
|
+
await writeFile(resolve(temp, 'diff-after.har'), JSON.stringify({ log: { entries: [entry('after')] } }));
|
|
284
|
+
const result = run(process.execPath, [
|
|
285
|
+
resolve(packagePath, binPath), '--diff', '--before', 'diff-before.har', '--after', 'diff-after.har', '--values',
|
|
286
|
+
], temp);
|
|
287
|
+
if (result.status !== 0) throw new Error('Installed capture command failed to diff synthetic HARs.');
|
|
288
|
+
const diff = JSON.parse(result.stdout);
|
|
289
|
+
if (diff.changed?.[0]?.responseChanges?.[0]?.path !== '$.value'
|
|
290
|
+
|| diff.changed[0].responseChanges[0].before !== 'before'
|
|
291
|
+
|| diff.changed[0].responseChanges[0].after !== 'after') {
|
|
292
|
+
throw new Error('Installed capture command omitted compact changed values.');
|
|
293
|
+
}
|
|
294
|
+
return 'installed capture CLI returned compact before/after response values';
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function verifyPackagedRouteEvolution(packagePath, binPath) {
|
|
298
|
+
const entry = (method, path) => ({
|
|
299
|
+
_resourceType: 'fetch',
|
|
300
|
+
request: { method, url: `https://tenant.synthetic.invalid/_api/${path}`, queryString: [] },
|
|
301
|
+
response: { status: 200, content: { mimeType: 'application/json', text: '{"value":[]}' } },
|
|
302
|
+
});
|
|
303
|
+
await writeFile(resolve(temp, 'route-baseline.har'), JSON.stringify({ log: { entries: [entry('GET', 'web')] } }));
|
|
304
|
+
await writeFile(resolve(temp, 'route-current.har'), JSON.stringify({ log: { entries: [entry('GET', 'web'), entry('POST', 'web/GetClientSideComponents')] } }));
|
|
305
|
+
const result = run(process.execPath, [
|
|
306
|
+
resolve(packagePath, binPath), '--summary', '--capture', 'route-current.har', '--baseline', 'route-baseline.har', '--no-values',
|
|
307
|
+
], temp);
|
|
308
|
+
if (result.status !== 0) throw new Error('Installed capture command failed to compare route-family baselines.');
|
|
309
|
+
const evolution = JSON.parse(result.stdout).apiReview?.evolution;
|
|
310
|
+
if (evolution?.newSinceBaseline?.length !== 1
|
|
311
|
+
|| evolution.newSinceBaseline[0].routeFamily !== 'POST web/GetClientSideComponents'
|
|
312
|
+
|| evolution.newSinceBaseline[0].status !== 'new-observation-review-source'
|
|
313
|
+
|| !evolution.note.includes('does not prove the API is undocumented')) {
|
|
314
|
+
throw new Error('Installed capture command failed to identify a newly observed route family for source review.');
|
|
315
|
+
}
|
|
316
|
+
return 'installed capture CLI compared dated route families and queued a new route for source review';
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
if (manifest.name !== '@spfx-fast/spfx-workbench') throw new Error('The package name must remain @spfx-fast/spfx-workbench.');
|
|
321
|
+
if (manifest.private === true || manifest.publishConfig?.access !== 'public') {
|
|
322
|
+
throw new Error('The package must be publishable as a public npm package.');
|
|
323
|
+
}
|
|
324
|
+
const packed = run('npm', ['pack', '--json', '--pack-destination', temp], packageRoot);
|
|
325
|
+
if (packed.status !== 0) throw new Error('npm pack failed.');
|
|
326
|
+
const pack = JSON.parse(packed.stdout)[0];
|
|
327
|
+
const packedPaths = new Set(pack.files.map(({ path }) => path));
|
|
328
|
+
const allowedRoots = [...new Set(['package.json', 'README.md', 'LICENSE', ...(manifest.files ?? [])])];
|
|
329
|
+
const unexpected = [...packedPaths].filter((path) => !allowedRoots.some((allowed) =>
|
|
330
|
+
path === allowed || (allowed.endsWith('/') && path.startsWith(allowed)) || path.startsWith(`${allowed}/`),
|
|
331
|
+
));
|
|
332
|
+
if (unexpected.length) throw new Error(`The tarball includes paths outside package files: ${unexpected.join(', ')}.`);
|
|
333
|
+
const excluded = pack.files.some(({ path }) => /(^|\/)(tests|reports|captures|SPECS)(\/|$)/.test(path));
|
|
334
|
+
if (excluded) throw new Error('The tarball includes development-only files.');
|
|
335
|
+
const requiredPaths = [
|
|
336
|
+
'package.json', 'README.md', 'LICENSE', 'index.html', 'vite.config.js',
|
|
337
|
+
'docs/mock-data-and-capture.md', 'docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md', 'fixtures/library-items.synthetic.json',
|
|
338
|
+
'scripts/mock-contract.mjs', 'scripts/diff-captures.mjs', 'src/simulator-context.mjs', 'src/spfx-preview-shims.mjs',
|
|
339
|
+
'src/auth-state.mjs',
|
|
340
|
+
...Object.values(manifest.bin ?? {}).map((path) => path.replace(/^\.\//, '')),
|
|
341
|
+
];
|
|
342
|
+
for (const path of requiredPaths) {
|
|
343
|
+
if (!packedPaths.has(path)) throw new Error(`The tarball is missing a required consumer file: ${path}.`);
|
|
344
|
+
}
|
|
345
|
+
if (manifest.license !== 'MIT') throw new Error('The package manifest and license gate currently require MIT.');
|
|
346
|
+
const sourceLicense = (await readFile(resolve(packageRoot, 'LICENSE'), 'utf8')).replace(/\r\n/g, '\n');
|
|
347
|
+
if (!sourceLicense.startsWith('MIT License\n') || !sourceLicense.includes('Permission is hereby granted, free of charge')) {
|
|
348
|
+
throw new Error('The source LICENSE file does not match the declared MIT license.');
|
|
349
|
+
}
|
|
350
|
+
if (manifest.engines?.node !== '^20.19.0 || >=22.12.0') throw new Error('Package metadata must declare Vite 8\'s supported Node.js range.');
|
|
351
|
+
for (const binPath of Object.values(manifest.bin ?? {})) {
|
|
352
|
+
if (!packedPaths.has(binPath.replace(/^\.\//, ''))) throw new Error(`The tarball is missing a declared executable: ${binPath}`);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
await writeFile(resolve(temp, 'package.json'), JSON.stringify({ name: 'spfx-workbench-tarball-check', version: '1.0.0', private: true }));
|
|
356
|
+
const packageFile = resolve(temp, pack.filename);
|
|
357
|
+
const installStartedAt = performance.now();
|
|
358
|
+
const installed = run('npm', ['install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-dev', packageFile], temp);
|
|
359
|
+
if (installed.status !== 0) throw new Error(`Clean consumer installation failed (exit ${installed.status}).`);
|
|
360
|
+
const installMs = performance.now() - installStartedAt;
|
|
361
|
+
|
|
362
|
+
const packagePath = resolve(temp, 'node_modules', ...manifest.name.split('/'));
|
|
363
|
+
const installedManifest = JSON.parse(await readFile(resolve(packagePath, 'package.json'), 'utf8'));
|
|
364
|
+
if (installedManifest.engines?.node !== manifest.engines.node) throw new Error('The packed package lost its Node.js engine requirement.');
|
|
365
|
+
const installedLicense = (await readFile(resolve(packagePath, 'LICENSE'), 'utf8')).replace(/\r\n/g, '\n');
|
|
366
|
+
if (installedLicense !== sourceLicense) throw new Error('The installed package license does not match the reviewed source license.');
|
|
367
|
+
const authApi = run(process.execPath, ['--input-type=module', '-e', "import { resolveTenantAuthStatePath } from '@spfx-fast/spfx-workbench/auth'; if (resolveTenantAuthStatePath('workswithagents').replaceAll('\\\\', '/').endsWith('/.playwright-auth/workswithagents.json') !== true) process.exit(1)"], temp);
|
|
368
|
+
if (authApi.status !== 0) throw new Error('The installed shared tenant-auth API could not resolve its cross-project state path.');
|
|
369
|
+
for (const command of Object.keys(installedManifest.bin ?? {})) {
|
|
370
|
+
const help = run('npm', ['exec', '--offline', '--', command, '--help'], temp);
|
|
371
|
+
if (help.status !== 0 || !help.stdout.includes(`Usage: ${command}`)) throw new Error(`Installed npm shim ${command} failed its help check.`);
|
|
372
|
+
}
|
|
373
|
+
const previewBin = installedManifest.bin?.['spfx-workbench'];
|
|
374
|
+
if (!previewBin) throw new Error('The installed package has no spfx-workbench command.');
|
|
375
|
+
const previewTimings = await verifyPackagedPreview(packagePath, previewBin);
|
|
376
|
+
const packagedCaptureDiff = await verifyPackagedCaptureDiff(packagePath, installedManifest.bin?.['spfx-workbench-capture']);
|
|
377
|
+
const packagedRouteEvolution = await verifyPackagedRouteEvolution(packagePath, installedManifest.bin?.['spfx-workbench-capture']);
|
|
378
|
+
await verifyPackagedSPHttpClient(packagePath);
|
|
379
|
+
await verifyPackagedDebugLauncher(packagePath, installedManifest.bin?.['spfx-workbench-debug']);
|
|
380
|
+
await verifyPackagedDoctor(packagePath, installedManifest.bin?.['spfx-workbench-doctor']);
|
|
381
|
+
await verifyPackagedHeftTarget(packagePath, installedManifest.bin?.['spfx-workbench-heft-target']);
|
|
382
|
+
|
|
383
|
+
process.stdout.write(`${JSON.stringify({
|
|
384
|
+
result: 'passed', package: manifest.name, version: manifest.version, packagePrivate: false,
|
|
385
|
+
files: pack.files.length, packedBytes: pack.size, unpackedBytes: pack.unpackedSize,
|
|
386
|
+
installedCommands: Object.keys(installedManifest.bin ?? {}),
|
|
387
|
+
packagedPreview: 'consumer component, props/context wrapper, captured HAR replay, and synthetic fallback passed',
|
|
388
|
+
setupMeasurement: {
|
|
389
|
+
status: 'success', samples: 1, installMs: Number(installMs.toFixed(2)),
|
|
390
|
+
previewReadyMs: Number(previewTimings.previewReadyMs.toFixed(2)),
|
|
391
|
+
timeToFirstUsablePreviewMs: Number((installMs + previewTimings.usablePreviewMs).toFixed(2)),
|
|
392
|
+
milestone: 'npm install start through packaged component wrapper and fixture replay',
|
|
393
|
+
packageShasum: pack.shasum,
|
|
394
|
+
node: process.version, platform: `${platform()}-${arch()}`,
|
|
395
|
+
note: 'single local warm-cache sample; baseline comparison not available',
|
|
396
|
+
},
|
|
397
|
+
packagedCaptureDiff,
|
|
398
|
+
packagedRouteEvolution,
|
|
399
|
+
packagedSPHttpClient: 'local synthetic GETs, cross-tenant replay, and captured RenderListDataAsStream POST policy passed',
|
|
400
|
+
packedContentsReviewed: 'packed paths match package files; required consumer files and declared binaries are present',
|
|
401
|
+
packagedLicense: 'MIT manifest, source license, and installed license match',
|
|
402
|
+
packagedDebugLauncher: 'consumer-local synthetic Heft start, option forwarding, preview readiness, and coordinated shutdown passed',
|
|
403
|
+
packagedDoctor: 'installed doctor reported supported SPFx, React, and Node.js compatibility from synthetic consumer metadata',
|
|
404
|
+
packagedHeftTarget: 'installed Heft target command resolved the synthetic tenant placeholder and preserved pageUrl provenance',
|
|
405
|
+
developmentFilesExcluded: true,
|
|
406
|
+
installFlags: ['--ignore-scripts', '--no-audit', '--no-fund'],
|
|
407
|
+
}, null, 2)}\n`);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
process.stderr.write(`Tarball check failed: ${error.message}\n`);
|
|
410
|
+
process.exitCode = 1;
|
|
411
|
+
} finally {
|
|
412
|
+
await rm(temp, { recursive: true, force: true });
|
|
413
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { readFile, readdir, realpath } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { MOCK_COVERAGE } from './mock-contract.mjs';
|
|
4
|
+
import { checkSPFxNodeRuntime } from './spfx-node-runtime.mjs';
|
|
5
|
+
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const componentArg = args.includes('--component') ? args[args.indexOf('--component') + 1] : undefined;
|
|
8
|
+
const propsFileArg = args.includes('--props-file') ? args[args.indexOf('--props-file') + 1] : undefined;
|
|
9
|
+
const root = resolve(process.cwd());
|
|
10
|
+
|
|
11
|
+
function inside(rootPath, targetPath) {
|
|
12
|
+
const path = relative(rootPath, targetPath);
|
|
13
|
+
return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function readJson(path) {
|
|
17
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function installedVersion(name) {
|
|
21
|
+
try {
|
|
22
|
+
const path = resolve(root, 'node_modules', ...name.split('/'), 'package.json');
|
|
23
|
+
return (await readJson(path)).version ?? null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function installedSPFxPackages() {
|
|
30
|
+
const packages = new Map();
|
|
31
|
+
const visited = new Set();
|
|
32
|
+
async function scanModules(modulesPath) {
|
|
33
|
+
let canonical;
|
|
34
|
+
try { canonical = await realpath(modulesPath); } catch { return; }
|
|
35
|
+
if (visited.has(canonical)) return;
|
|
36
|
+
visited.add(canonical);
|
|
37
|
+
let entries;
|
|
38
|
+
try { entries = await readdir(modulesPath, { withFileTypes: true }); } catch { return; }
|
|
39
|
+
const packagePaths = [];
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
const entryPath = resolve(modulesPath, entry.name);
|
|
42
|
+
if (entry.name.startsWith('@')) {
|
|
43
|
+
let scoped;
|
|
44
|
+
try { scoped = await readdir(entryPath, { withFileTypes: true }); } catch { continue; }
|
|
45
|
+
for (const child of scoped) packagePaths.push(resolve(entryPath, child.name));
|
|
46
|
+
} else {
|
|
47
|
+
packagePaths.push(entryPath);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const packagePath of packagePaths) {
|
|
51
|
+
try {
|
|
52
|
+
const metadata = await readJson(resolve(packagePath, 'package.json'));
|
|
53
|
+
if (/^@microsoft\/sp-[a-z0-9-]+$/.test(metadata.name ?? '')) {
|
|
54
|
+
const instances = packages.get(metadata.name) ?? [];
|
|
55
|
+
instances.push({ version: metadata.version ?? null });
|
|
56
|
+
packages.set(metadata.name, instances);
|
|
57
|
+
}
|
|
58
|
+
} catch {}
|
|
59
|
+
await scanModules(resolve(packagePath, 'node_modules'));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
await scanModules(resolve(root, 'node_modules'));
|
|
63
|
+
return packages;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function checkVersion(name, version, supported) {
|
|
67
|
+
if (!version) return { name, status: 'unknown', version: null, expected: supported };
|
|
68
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:\+.*)?$/.exec(version);
|
|
69
|
+
if (!match) return { name, status: 'unknown', version, expected: supported };
|
|
70
|
+
const [major, minor, patch] = match.slice(1).map(Number);
|
|
71
|
+
const ok = name.startsWith('@microsoft/sp-')
|
|
72
|
+
? major === 1 && minor >= 24
|
|
73
|
+
: major === 18 && minor === 3 && patch === 1;
|
|
74
|
+
return { name, status: ok ? 'supported' : 'unsupported', version, expected: supported };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function diagnose() {
|
|
78
|
+
const manifest = await readJson(resolve(root, 'package.json'));
|
|
79
|
+
const declaredDependencies = Object.keys({
|
|
80
|
+
...manifest.dependencies,
|
|
81
|
+
...manifest.devDependencies,
|
|
82
|
+
...manifest.optionalDependencies,
|
|
83
|
+
});
|
|
84
|
+
const declaredSPFxPackages = [...new Set([
|
|
85
|
+
...declaredDependencies.filter((name) => /^@microsoft\/sp-[a-z0-9-]+$/.test(name)),
|
|
86
|
+
'@microsoft/sp-webpart-base',
|
|
87
|
+
])].sort();
|
|
88
|
+
const [installedSPFx, reactVersion, reactDomVersion] = await Promise.all([
|
|
89
|
+
installedSPFxPackages(),
|
|
90
|
+
installedVersion('react'),
|
|
91
|
+
installedVersion('react-dom'),
|
|
92
|
+
]);
|
|
93
|
+
const spfxPackages = [...new Set([...declaredSPFxPackages, ...installedSPFx.keys()])].sort();
|
|
94
|
+
const spfxByName = Object.fromEntries(spfxPackages.map((name) => [
|
|
95
|
+
name,
|
|
96
|
+
installedSPFx.get(name)?.map(({ version }) => version) ?? [],
|
|
97
|
+
]));
|
|
98
|
+
const coreVersions = spfxByName['@microsoft/sp-core-library'] ?? [];
|
|
99
|
+
const coreVersion = coreVersions.length === 1 ? coreVersions[0] : null;
|
|
100
|
+
const results = [
|
|
101
|
+
...spfxPackages.map((name) => {
|
|
102
|
+
const versions = spfxByName[name];
|
|
103
|
+
const checks = versions.map((version) => checkVersion(name, version, 'SPFx 1.24 or newer'));
|
|
104
|
+
return {
|
|
105
|
+
name,
|
|
106
|
+
status: checks.length === 0 ? 'unknown' : checks.every((check) => check.status === 'supported') ? 'supported' : 'unsupported',
|
|
107
|
+
version: versions.length === 1 ? versions[0] : null,
|
|
108
|
+
versions,
|
|
109
|
+
expected: 'SPFx 1.24 or newer',
|
|
110
|
+
};
|
|
111
|
+
}),
|
|
112
|
+
checkVersion('react', reactVersion, '18.3.1'),
|
|
113
|
+
checkVersion('react-dom', reactDomVersion, '18.3.1'),
|
|
114
|
+
checkSPFxNodeRuntime(coreVersion, process.versions.node),
|
|
115
|
+
{
|
|
116
|
+
name: 'spfx-package-alignment',
|
|
117
|
+
status: spfxPackages.some((name) => spfxByName[name].length === 0 || spfxByName[name].some((version) => !version)) || !coreVersion
|
|
118
|
+
? 'unknown'
|
|
119
|
+
: spfxPackages.every((name) => spfxByName[name].every((version) => version === coreVersion)) ? 'supported' : 'unsupported',
|
|
120
|
+
versions: spfxByName,
|
|
121
|
+
expected: 'all installed @microsoft/sp-* package instances use the same exact version as @microsoft/sp-core-library',
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
name: 'simulator-context-contract',
|
|
125
|
+
status: !spfxByName['@microsoft/sp-webpart-base']?.length
|
|
126
|
+
? 'unknown'
|
|
127
|
+
: spfxByName['@microsoft/sp-webpart-base'].every((version) => version === '1.24.1')
|
|
128
|
+
? 'supported'
|
|
129
|
+
: spfxByName['@microsoft/sp-webpart-base'].some((version) => checkVersion('@microsoft/sp-webpart-base', version, 'SPFx 1.24 or newer').status === 'unsupported')
|
|
130
|
+
? 'unsupported'
|
|
131
|
+
: 'unknown',
|
|
132
|
+
versions: spfxByName['@microsoft/sp-webpart-base'] ?? [],
|
|
133
|
+
sourceVersion: MOCK_COVERAGE.context.version,
|
|
134
|
+
expected: 'context declaration coverage is verified for SPFx 1.24.1; source review is required for other supported releases',
|
|
135
|
+
},
|
|
136
|
+
];
|
|
137
|
+
if (componentArg) {
|
|
138
|
+
try {
|
|
139
|
+
const component = await realpath(resolve(root, componentArg));
|
|
140
|
+
const localEntry = inside(await realpath(root), component) && /\.[jt]sx?$/.test(component);
|
|
141
|
+
results.push({
|
|
142
|
+
name: 'component-entry',
|
|
143
|
+
status: localEntry ? 'supported' : 'unsupported',
|
|
144
|
+
path: localEntry ? relative(await realpath(root), component) : null,
|
|
145
|
+
expected: 'JS, JSX, TS, or TSX file inside the consumer project',
|
|
146
|
+
});
|
|
147
|
+
if (localEntry) {
|
|
148
|
+
const source = await readFile(component, 'utf8');
|
|
149
|
+
const nativeWebPart = /\bBaseClientSideWebPart\b/.test(source);
|
|
150
|
+
const lifecycle = ['onInit', 'render', 'onAfterResize', 'onDispose', 'onDisplayModeChanged', 'onPropertyPaneConfigurationStart', 'onPropertyPaneConfigurationComplete']
|
|
151
|
+
.filter((name) => new RegExp(`\\b${name}\\s*\\(`).test(source));
|
|
152
|
+
const sdkReferences = ['aadHttpClientFactory', 'aadTokenProviderFactory', 'msGraphClientFactory', 'httpClient', 'dynamicDataProvider', 'dynamicDataSourceManager']
|
|
153
|
+
.filter((name) => new RegExp(`\\b${name}\\b`).test(source));
|
|
154
|
+
if (/\bsdks\s*\.\s*microsoftTeams\s*\.\s*(?:teamsJs|context)\b/.test(source)) sdkReferences.push('sdks.microsoftTeams SDK API');
|
|
155
|
+
results.push({
|
|
156
|
+
name: 'spfx-lifecycle-adapter',
|
|
157
|
+
status: nativeWebPart || lifecycle.some((name) => ['onInit', 'onAfterResize', 'onDispose'].includes(name)) ? 'partial' : 'not-applicable',
|
|
158
|
+
detectedNativeBaseClass: nativeWebPart,
|
|
159
|
+
detectedMethods: lifecycle,
|
|
160
|
+
invokedMethods: ['onInit', 'render', 'onAfterResize', 'onDispose'],
|
|
161
|
+
unsupportedMethods: ['onDisplayModeChanged', 'onPropertyPaneConfigurationStart', 'onPropertyPaneConfigurationComplete'],
|
|
162
|
+
expected: 'lifecycle adapter invokes init, render, resize, and dispose; SharePoint property pane and display-mode host behavior is unavailable',
|
|
163
|
+
});
|
|
164
|
+
results.push({
|
|
165
|
+
name: 'spfx-sdk-clients',
|
|
166
|
+
status: sdkReferences.length ? 'unsupported' : 'not-detected',
|
|
167
|
+
detectedReferences: sdkReferences,
|
|
168
|
+
expected: 'SharePoint service-scope clients, AAD/Graph factories, and Teams SDK methods require Heft on a SharePoint page; checking whether the simulator runs inside Teams is supported',
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
} catch {
|
|
172
|
+
results.push({ name: 'component-entry', status: 'unsupported', path: null, expected: 'existing JS, JSX, TS, or TSX file inside the consumer project' });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (args.includes('--props-file')) {
|
|
176
|
+
try {
|
|
177
|
+
const canonicalRoot = await realpath(root);
|
|
178
|
+
const propsPath = await realpath(resolve(root, propsFileArg ?? ''));
|
|
179
|
+
const relativePath = relative(canonicalRoot, propsPath);
|
|
180
|
+
if (!inside(canonicalRoot, propsPath) || !/\.json$/i.test(propsPath)) {
|
|
181
|
+
throw new Error('outside-root');
|
|
182
|
+
}
|
|
183
|
+
const source = await readFile(propsPath);
|
|
184
|
+
if (source.byteLength > 1_000_000) throw new Error('too-large');
|
|
185
|
+
const props = JSON.parse(source.toString('utf8'));
|
|
186
|
+
if (!props || typeof props !== 'object' || Array.isArray(props)) throw new Error('not-object');
|
|
187
|
+
const contextOverride = Object.hasOwn(props, 'context');
|
|
188
|
+
results.push({
|
|
189
|
+
name: 'props-file',
|
|
190
|
+
status: contextOverride ? 'unsupported' : 'supported',
|
|
191
|
+
path: relativePath,
|
|
192
|
+
propertyNames: Object.keys(props).filter((name) => name !== 'context'),
|
|
193
|
+
contextOverride,
|
|
194
|
+
expected: 'project-local JSON object without a context property; values are not reported',
|
|
195
|
+
});
|
|
196
|
+
} catch (error) {
|
|
197
|
+
results.push({
|
|
198
|
+
name: 'props-file', status: 'unsupported', path: null, propertyNames: [], contextOverride: false,
|
|
199
|
+
expected: error.message === 'too-large'
|
|
200
|
+
? 'JSON props file no larger than 1 MB'
|
|
201
|
+
: 'existing project-local JSON object without a context property',
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
schema: 'spfx-workbench-diagnostics/v1',
|
|
207
|
+
project: manifest.name ?? null,
|
|
208
|
+
evidence: 'installed package metadata across nested node_modules and canonical component path; unknown means a required dependency is not installed or its version cannot be read',
|
|
209
|
+
checks: results,
|
|
210
|
+
mockCoverage: MOCK_COVERAGE,
|
|
211
|
+
summary: results.some((check) => check.status === 'unsupported')
|
|
212
|
+
? 'unsupported'
|
|
213
|
+
: results.some((check) => ['unknown', 'partial'].includes(check.status)) ? 'incomplete' : 'supported',
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
218
|
+
process.stdout.write('Usage: spfx-workbench-doctor [--component <project-relative-file>] [--props-file <project-relative-json>]\nReports SPFx package alignment, React versions, pinned simulator context and mock coverage, component entry, and props-file shape.\n');
|
|
219
|
+
} else {
|
|
220
|
+
try {
|
|
221
|
+
const result = await diagnose();
|
|
222
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
223
|
+
if (result.summary === 'unsupported') process.exitCode = 1;
|
|
224
|
+
} catch (error) {
|
|
225
|
+
process.stderr.write(`SPFx Workbench diagnostics failed: ${error.message}\n`);
|
|
226
|
+
process.exitCode = 2;
|
|
227
|
+
}
|
|
228
|
+
}
|