@spfx-fast/spfx-workbench
v0.1.5
Published
Local SPFx component preview, diagnostics, SharePoint API capture and replay, and Heft debugging tools.
Maintainers
Readme
SPFx Workbench
Build and debug SharePoint Framework (SPFx) components with a local preview, focused diagnostics, and tools for working with real SharePoint behavior. Workbench can replay captured API responses, reuse an existing browser storage state, and coordinate the project's Heft workflow.
Start with the IDE router for the agent workflow, or install Workbench directly in an SPFx project:
npm install --save-dev @spfx-fast/spfx-workbench
npx spfx-workbench --component src/components/HelloWorld.tsxThe local canvas is a fast development aid, not a full SharePoint host. It renders compatible React components and a documented subset of SPFx lifecycle/context behavior; use the real SharePoint page when validating host integration. Workbench is a developer tool, not a security or credential scanner.
Run locally
Use Node.js ^20.19.0 || >=22.12.0 (Vite's supported range), then:
npm install
npm run devVite serves the preview on http://127.0.0.1:4173. npm run build builds the static prototype; npm run preview serves that build on port 4174. This package is a developer workflow tool, not a vulnerability, malware, or credential scanner.
Find the agent skill
The portable spfx-ide skill ships in packages/ide/skills/spfx-ide/SKILL.md. Try discovery with npx --yes skills add https://github.com/vystartasv/spfx-workbench --list; package keywords, README content, GitHub description, and topics also help people find the project. npm search indexing may take up to two weeks. skills.sh uses anonymous aggregate install counts for its leaderboard; installs do not guarantee a particular rank.
Current behavior
- SharePoint page-grid breakpoints at 320, 1024, 1366, and 1920 px, with a 1204 px content maximum; the documented 480, 640, and 768 px layouts are also supported. Sections reflow to one, two, or three columns. The local section-width control provides one-third, one-half, two-thirds, full-page, and full-screen widths; ratio presets expand on narrow screens. These ratio presets are a workbench convenience, not a claim about native SharePoint section types.
- A circled plus sits between sections. It inserts a new section at that position, matching Microsoft's documented section-border affordance. Touch targets are at least 44 × 44 px.
- Section background choices are None, Neutral, Soft, and Strong. The local theme picker starts with SharePoint blue and includes Teal and Purple preview palettes; these are local presets, not a connected tenant's theme.
- The synthetic Document Library web part supports List, Compact list, and Tiles views, filtering, and a visible fixture/capture source. “Local simulation” labels make clear that no tenant host context or APIs are active.
- Mock list rows follow the SP REST
value[]shape forId,Title,FileLeafRef, andModified;Iduses theEdm.Int32range, and displayed timestamps use an explicit UTC format for repeatable rendering. - Local preview requests use the committed synthetic library fixture or an ignored local override; consumer
spHttpClientcalls use captured local replay or declared synthetic fallbacks. - When
--componentis supplied, the consumer component appears in the first section of this editor; toolbox, section settings, and the property pane stay available. React Fast Refresh updates the component locally, not a web part running on a SharePoint page.
Preview a consumer component
The npm package name is @spfx-fast/spfx-workbench. Install it in an SPFx project and run the CLI from that project's root:
npm install --save-dev @spfx-fast/spfx-workbench
npx spfx-workbench --component src/components/HelloWorld.tsxTo test changes from this repository, install the local repository path instead.
The registry install command is:
npm install --save-dev @spfx-fast/spfx-workbenchPass deterministic component props from a project-local JSON object no larger than 1 MB with --props-file:
npx spfx-workbench --component src/components/HelloWorld.tsx --props-file .spfx-workbench/preview-props.jsonThe wrapper passes those values as React component props and supplies its own context; a props file cannot override it. Class-based web parts use a local lifecycle adapter. The typed SimulatorContext subset is documented in src/contracts/simulator-context.d.ts: fixed pageContext.web/site/user values, stable instanceId, domElement, manifest, edit displayMode, local SharePoint-host indicators, read-only spHttpClient.get, and captured read-only spHttpClient.post routes. It is derived from pinned SPFx 1.24.1 declarations. The doctor reports this declaration coverage as unknown for other releases. Common public runtime imports in generated SPFx web parts use small simulator shims; localizedResources from config/config.json resolves the en-us resource, falling back to its matching src file before a Heft build. The local preview does not load the real SharePoint host or package internals. Values are fixed synthetic placeholders. Unsupported context reads and mutation attempts throw diagnostics. The .test URLs and .invalid user are not tenant identity or permission evidence.
context.spHttpClient.get(url, configuration) replays HTTP(S) SharePoint /_api/ GET URLs from captured tenants by API path and query, preserving occurrence order, response status, body, and usable response headers. Captured read-only POST routes also replay by route and canonical JSON body for SiteUserInfoList/GetItems, RenderListDataAsStream, and RenderExtendedListFormData. The routes are capture-derived; Microsoft documents RenderListDataAsStream. During an active capture the simulator reads .spfx-workbench/captures/tenant-live.json; after capture it reads .spfx-workbench/captures/tenant.har. The Vite process refreshes its index when either file changes, so new responses can be replayed without restarting the preview. Host and site prefix are not part of the match key. Requests go only to the local replay server; Set-Cookie and transport headers are excluded from the localhost response. If no HAR entry matches, list-item, web-title, and documented list-metadata GETs use deterministic synthetic routes; other calls return a local 404. POST is not forwarded to SharePoint: page-write, coauthoring, and telemetry routes are rejected, request options are limited, and the simulator supplies no authentication or server-side state. Captured tenant responses stay verbatim in the ignored capture files. See capture and replay for matching and storage details.
The CLI serves on loopback port 4176 by default; use --port to choose another port. A default export may be a compatible React component or a class with SPFx-style onInit, render, onAfterResize, and onDispose methods. The local lifecycle adapter runs initialization, render, resize, and disposal hooks. It does not construct the SharePoint service scope, invoke property pane or display-mode lifecycle hooks, or load first-party web-part implementations. The spfx-workbench-doctor --component <file> command reports detected lifecycle methods and SDK/context gaps. The simulator supplies only the documented context subset; it does not create a full SPFx host or patch a live SharePoint web part. Fast Refresh is intended for component modules with consistent React component exports. With the pinned @vitejs/plugin-react, incompatible refresh boundaries produce a reasoned hmr invalidate diagnostic in the Vite terminal (for example, an incompatible export); if an update cannot be accepted, Vite may reload the page. See the plugin's consistent component export guidance. React Fast Refresh behavior in the local preview is separate from Heft rebuild and modern-page reload.
The consumer component is rendered inside the first section of the local page editor. Its nearest SPFx *.manifest.json supplies the displayed title and “In development” label. The toolbox contains the component and the deterministic document library fixture. SharePoint built-in web parts run when loaded by SharePoint; this canvas does not imitate them. Section controls remain local and file edits use React Fast Refresh. This canvas does not modify a SharePoint page. For whole-page traffic, use the Playwright HAR workflow below; that records the browser context, including web parts and extensions.
The CLI serves only on loopback and limits Vite filesystem requests to the workbench package and consumer project. It resolves the selected component and every Vite /@fs/ request through real paths so symlinks cannot expand that boundary. Synthetic captures are read from the consumer project's .spfx-workbench/captures/; add that directory to a repository .gitignore file before importing. The importer verifies that a repository .gitignore rule covers both the final capture and its temporary file; it does not accept a machine-wide or repository-private exclude as a substitute.
Inspect the consumer's installed runtime versions and an optional component entry before previewing:
npx spfx-workbench-doctor --component src/components/HelloWorld.tsx --props-file .spfx-workbench/preview-props.jsonThe command emits JSON with per-check supported, unsupported, or unknown status plus mock coverage and provenance. For a props file, it reports the project-relative path and property names, never values, and flags a context override. It scans installed @microsoft/sp-* packages, including nested node_modules, accepts SPFx 1.x packages and reports package alignment separately. React 17 and 18 are recognized; other versions are flagged for review. Microsoft’s documented SPFx 1.24.1 Node.js range (22.14+ within 22.x, 24.x, or 26.x) is advisory and unknown for other releases. It never blocks Workbench on a consumer Node mismatch. Workbench itself requires Node ^20.19.0 || >=22.12.0 for Vite 8. The Heft launcher uses the consumer’s installed CLI without a version pin and applies to Heft-based SPFx projects (1.22+); older Gulp-era projects can use preview on a best-effort basis. Missing package metadata is unknown and summarized as incomplete. It does not test every SPFx behavior or infer component prop types/API usage.
This is an early consumer-loader slice. It supports explicit JSON props and the documented read-only simulator context subset; it does not create full SPFx host context or infer an arbitrary TypeScript props contract. Broader SPFx compatibility checks and live SharePoint validation remain incomplete.
How this fits with the SPFx Fast tools
Use @spfx-fast/ide as the thin developer and agent entry point. The spfx-ide CLI routes to focused tools; installation as a project devDependency or globally places Agent Skills guidance in supported skill directories unless lifecycle scripts are disabled. This confirms file placement, not discovery by every agent; check the agent's own skills list where available. Global CLI use also needs npm's global bin directory on PATH. Workbench owns component preview, synthetic context/API replay, diagnostics, capture, and Heft launch. The focused companion packages have separate jobs:
@spfx-fast/playwrightruns authenticated browser tests against a real SharePoint page.@spfx-fast/knowledgeprovides the SPFx agent skill and debugging references; use it to guide the tools, not as a runtime dependency.@spfx-fast/idedepends on the focused Playwright and knowledge packages and routes to optional artifact and recurring-fix tools when installed.@spfx-fast/coreand@spfx-fast/sharepoint-uiare optional application libraries. Workbench does not require either.agent-efficiency-toolsandhermes-harnessare optional repository-level agent utilities, not Workbench dependencies.
Keep dependencies pointed from an application or tool to code it imports. Link the tools through install guidance and agent knowledge when no shared runtime code is needed.
Capture and replay
Whole-page SharePoint HAR
Install the package in the consuming project and add .spfx-workbench/captures/ to that project's .gitignore. Tenant states live once per user under ~/.playwright-auth/<tenant>.json (resolved from the OS home directory) and can be reused by every project. The integrated command can sign in, refresh, and check state without printing cookie values:
npx spfx-workbench-auth login workswithagents --fresh
npx spfx-workbench-auth refresh workswithagents
npx spfx-workbench-auth check workswithagentslogin --fresh opens a clean Playwright browser. Complete Microsoft sign-in yourself and choose Yes for “Stay signed in?”. The existing JSON is replaced only after SharePoint confirms the sign-in. refresh loads the saved state and rewrites it only after the tenant confirms the session; check is read-only. POSIX files are written with mode 600; Windows uses the current user's inherited ACL. The package exposes @spfx-fast/spfx-workbench/auth so project scripts can use the same tenant state:
import { launchTenantBrowser } from '@spfx-fast/spfx-workbench/auth';
const { browser, context, close } = await launchTenantBrowser('workswithagents', {
headless: true,
contextOptions: { viewport: { width: 1023, height: 900 } },
});
const page = await context.newPage();
try { await page.goto('https://workswithagents.sharepoint.com/sites/spfx-validation-lab'); }
finally { await close(); }The capture command accepts a tenant name to reuse this shared state, or an explicit --storage-state path for a separate state file:
npx spfx-workbench-capture --watch \
--page 'https://tenant.sharepoint.com/sites/site/SitePages/page.aspx' \
--tenant workswithagents --edit --duration 30The capture writes an incrementally refreshed .spfx-workbench/captures/tenant-live.json containing fetch/XHR calls while recording the full page, web-part, and extension traffic into .spfx-workbench/captures/tenant.har. Before replacing an existing HAR, capture archives it; after capture it archives the new HAR too. Archives stay in the ignored capture directory until removed. Component replay reads the live API snapshot as it changes; full-page replay reads the current HAR and automatically loads older local archives. Capture and replay use the package's Playwright-managed Chromium, installed on first use, on macOS, Windows, and Linux. --duration <seconds> ends a recording after the page loads and edit-mode entry is attempted; it accepts 1–3600 seconds. --once keeps the four-second default. --measure additionally records section/web-part geometry and spacing at 320, 390, 639, 640, 768, 1023, 1024, 1366, and 1920 px in the ignored .spfx-workbench/captures/tenant-measurements.json. Captured HARs and auth JSON remain local under .gitignore and the home directory. Cross-platform paths are implemented; this checkout's automated browser evidence is from macOS only.
See mock-data-and-capture.md for the capture and replay command details.
New captures include a versioned manifest and API initiator trace; compare dated HARs with --diff as SharePoint changes.
Replay the page offline at a chosen viewport:
npx spfx-workbench-replay --capture .spfx-workbench/captures/tenant.har --width 1023 --height 900 --onceReplay automatically loads the local dated archive. Use repeated --fallback-capture flags only for HARs stored elsewhere; the current capture takes precedence.
Inventory captured API calls in request order without printing body values:
npx spfx-workbench-capture --summary --capture .spfx-workbench/captures/tenant.har \
--initiators .spfx-workbench/captures/tenant-initiators.json --no-valuesThe summary includes fetch/XHR calls, repeated-call numbers, resource type, status, byte counts, JSON request/response shapes, and masked SharePoint route families in request order. --initiators joins each route to compact script-callsite evidence from the matching CDP trace. Add --baseline <earlier.har> to report newly observed route families, routes not present in the current page capture, and counts for shared routes. New routes are queued for source review; that does not establish they are undocumented. Use --values for bounded input/output values (each JSON value is capped at 512 bytes with a short preview when larger), or --raw-values for up to 1,000 characters per body. The full HAR remains the source for offline page rendering. See the dated 2026-11-15 SharePoint behavior snapshot for the captured edit-mode call order and evidence status.
Replay uses Playwright's HAR routing, blocks service workers so their requests cannot bypass replay, and aborts requests missing from the capture. It reports response status counts, failed request origins and paths (without query strings), page errors, canvas/webpart counts, and viewport overflow. Playwright routing disables the browser HTTP cache; the HAR itself is the replay cache. Repeated calls to the same method and URL are preserved in the compact before/after diff:
npx spfx-workbench-capture --diff \
--before .spfx-workbench/captures/before.har \
--after .spfx-workbench/captures/tenant.harAdd --values when the agent needs to see what changed: it includes before/after values for changed JSON paths and compact values for added/removed calls. Large values are bounded. --raw-values includes the original request/response body text (up to 1,000 characters per body). The default reports paths, statuses, and byte counts while the complete HAR stays local.
Synthetic component API replay
The fixture shape follows Microsoft’s documented list-items request: $select=Id,Title,FileLeafRef,Modified. The committed fixture contains invented example rows. To create a local replay from your own synthetic-only response capture:
npm run capture:synthetic -- --input path/to/synthetic-capture.jsonThe importer accepts only a source marked synthetic, only GET list-item calls, only a successful status, only the four allowlisted fields, and input files up to 1 MB. It reads at most 1 MB plus one byte before rejecting oversized input. After saving, it prints a field-level contract diff showing retained allowlisted fields and how many unrecognized response fields were stripped; it never prints captured values or unknown field names. It drops request URLs, query strings other than the safe field selection/top count, headers, cookies, tokens, unrecognized fields, and response metadata. It requires repository .gitignore rules to cover both the final and temporary paths, rejects machine-wide and repository-private ignore substitutes, and rejects symlinked destination directories and output files. It atomically writes .spfx-workbench/captures/library-items.json without imposing a file-mode policy. The running Vite workbench picks up that file on its next request and labels it “Local capture”. Remove it to return to the committed generic fixture.
In a consumer project, import with npx spfx-workbench-capture --input path/to/synthetic-capture.json. Add .spfx-workbench/captures/ to a repository .gitignore file first; a machine-wide ignore or .git/info/exclude entry alone is not sufficient. The consumer CLI points replay at this project-local capture directory.
The dev and preview servers serve the mock response at /__spfx_workbench/api/library-items. It is a local-only fixture endpoint; it does not proxy or contact SharePoint. The captured-har benchmark exercises the local component replay endpoint against an existing capture and omits the request URL and query values from its output:
npm run benchmark:mock-api -- --route captured-har \
--url http://127.0.0.1:4176/__spfx_workbench/api/captured \
--request-url "$SPFX_CAPTURED_REQUEST_URL" --samples 50Measure the synthetic import path using isolated temporary Git consumers:
npm run benchmark:capture-import -- --samples 5The benchmark reports Node version, platform, architecture, sample count, and min/median/p95/max. It includes process startup, validation, the safe contract diff, the Git-ignore check, and the temporary local write. It does not contact SharePoint or use consumer data.
Check one component update through Vite's WebSocket module-update event:
npm run benchmark:consumer-hmrThe check edits a synthetic consumer component, measures its Vite update event, and confirms the transformed module contains the new revision. It also verifies the served React Refresh runtime and injects an incompatible-export reason through Vite's vite:invalidate handler to check the terminal diagnostic. The injected message does not prove browser detection or fallback. This check does not measure repeated edits, React application, state retention, navigation, or live SharePoint iteration; npm run check:browser-hmr exercises 20 real browser edits and checks those behaviors.
Verify React Fast Refresh in a real browser with:
npm run check:browser-hmrThe check uses Playwright-managed Chromium, installed on first use, and does not require a system Chrome path. It edits a synthetic consumer component 20 times at a 1023 px viewport and confirms each React update applies, component state survives every edit, and the page does not navigate. It then adds an incompatible named export and confirms Vite reports the boundary reason, the browser reloads once, and the updated component appears. It reports min, median, p95, and max for compatible browser updates; it does not measure the full developer workflow or SharePoint. Set --samples to an integer from 1 to 100. npm run check:responsive additionally checks the five local section-width options with a synthetic web part at nine viewport widths and verifies the insertion control on touch input. npm run check:release runs the local gates, browser HMR check, and responsive layout check. It still does not start real Heft or establish tenant parity.
Measure that endpoint while the dev server is running:
npm run benchmark:mock-api -- --samples 50
npm run benchmark:mock-api -- --route web-title --samples 50
npm run benchmark:mock-api -- --route lists --samples 50The warm-up request is excluded. list-items is the default route; add --select Id,Title --top 2 to measure a projected, limited response. web-title measures the separate /_api/web?$select=Title fixture. lists measures the documented /_api/web/lists projection/filter/order query. Use --url http://127.0.0.1:4175/__spfx_workbench/api/library-items to target another loopback server. Output is JSON with route, sample count, UTC timestamp, Node/Vite/platform versions, latency statistics, payload size, query, and fixture source. The command rejects non-loopback URLs. These are local synthetic timings, not SharePoint latency measures.
Real SharePoint debugging
SPFx 1.22+ uses Heft. The modern SharePoint page/debug-manifest flow is separate from this Vite preview. To start the local component preview and the consuming project's installed Heft together, run this from the consumer root:
npx spfx-workbench-debug --component src/webparts/example/Example.tsx -- --serve-config defaultThe launcher resolves the consumer's local @rushstack/heft before starting the preview, serves on loopback port 4176, verifies that Vite can transform the entry, simulator wrapper, and consumer component, then invokes that Heft installation's start command with options after --. If Heft is missing, the preview is not started. It will stop before Heft starts if the component cannot be transformed. Pass --port and --props-file before -- to configure the preview. Heft retains its normal behavior: a serve configuration may open its modern SharePoint page and prompt to allow debug scripts. For the web-part manifest flow, pass -- --nobrowser and follow Microsoft's instructions to open the modern page with loadSPFX=true and the local debugManifestsFile. Ctrl+C stops both processes. This does not authenticate, select a tenant target, modify a page, or patch a live web part; validate those steps in the consumer's normal authorized workflow.
To inspect a target configured by an existing SPFx project, run from that project's directory:
npx spfx-workbench-heft-target --serve-config defaultPass --config path/to/serve.json when the file is elsewhere. The command returns root initialPage when present; otherwise it returns the named serveConfigurations.<name>.pageUrl. For Microsoft's documented {tenantDomain} placeholder, it uses SPFX_SERVE_TENANT_DOMAIN and reports an actionable error if the variable is missing or malformed. It validates an absolute HTTP(S) target and gives a clear error for missing or malformed configurations. Add --json for a machine-readable result with the selected URL, source field, and configuration name. It does not alter or launch the URL. See Microsoft's Heft-based SPFx setup guidance for the environment variable format.
Microsoft’s current guidance: Debug SharePoint Framework solutions on modern SharePoint pages. Never use a production package pointed at localhost. Tenant-backed validation requires an active, authorized storage state and a confirmed target.
When the page is in edit mode during an SPFx debug session, the SharePoint Framework Developer Toolbar adds a Web Part menu for the selected part. It can show that instance's JSON, HTML, and manifest details; it can also open the developer dashboard. This is useful for matching a real web part's configuration and rendered markup. It does not export the whole page's theme, section geometry, or spacing, and the workbench does not automatically import these values. Treat JSON/HTML dumps as potentially sensitive; the synthetic capture importer does not accept them.
Project status
See the engineering report for implementation evidence, unmeasured baselines, and known gaps. Local section measurements list the synthetic editor's section/web-part dimensions; tenant page measurements list read-only live view-mode section/ControlZone boxes at nine viewport widths.
Run the automated local release checks together with:
npm run check:localThis builds the workbench, runs npm test (temporary-consumer regressions and a synthetic local-CDP auth capture check), measures 20 consumer Vite HMR events, and installs the clean npm tarball into a disposable consumer. It does not verify browser React apply/state retention; use npm run check:release for the additional Chrome gate. Neither command proves a real Heft session, live-page parity, or every release criterion below.
Inspect the packed package in a clean temporary consumer:
npm run check:tarballThis packs the source manifest, checks every packed path against package.json files, requires consumer docs/fixtures/source and all declared binaries, verifies the MIT license matches the installed tarball and manifest, and checks that the Node.js engine range survives packing. It installs the package as a devDependency, checks each npm command shim, launches the packaged preview with a synthetic consumer component and props file, verifies the context wrapper, captured HAR response replay, and synthetic fallback, runs compact HAR diff through the installed capture command, and confirms tests, reports, captures, and specs are absent. Its JSON result includes package contents/license checks, packaged diff results, and install/time-to-first-usable-preview timings. The engineering report records setup timings against artifact hashes; these local warm-cache samples do not establish a general setup success rate or baseline comparison.
Original simulator code is MIT licensed; see LICENSE.
