Skip to content

feat(playground): add Forge Web Playground and embed in forge-docs - #195

Open
teamchong wants to merge 47 commits into
mainfrom
feat/playground
Open

teamchong wants to merge 47 commits into
mainfrom
feat/playground

Conversation

@teamchong

@teamchong teamchong commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Adds packages/forge-playground, an in-browser OpenAPI 3.x compiler, SDK/CLI diff explorer, and interactive sandbox powered by forge compiled to wasm32-unknown-unknown, and embeds it directly in packages/docs (forge-docs) at /playground/.

packages/docs renders Docs and Playground header tabs beside the Forge lockup (packages/docs/src/components/Header.astro) and mounts a sidebarless full-viewport /playground/ route (packages/docs/src/pages/playground.astro) sharing Nimbus BaseLayout, Furnace light and dark tokens, and ClientRouter navigation. packages/docs dev and build scripts run packages/forge-playground/scripts/build.mjs --sync-docs before cf dev and cf build so Workers Builds branch previews, production deploys, and CI link checks include /playground/ and its compiled WASM, TypeScript compiler bundle, and compressed OpenAPI baseline under public/playground/.

The playground loads the published Cloudflare OpenAPI baseline (or runs standalone against any OpenAPI 3.0/3.1/3.2 document), computes before/after output diffs and cross-bundle conflict diagnostics across the TypeScript SDK, Cap'n Web, IR Inspector, cf CLI, and custom TypeScript plugin targets, and includes in-browser "Try in TS" typechecking and "Try cf CLI" dry-run execution. Also adds packages/forge-playground/scripts/encode-link.mjs for generating compressed #s= / ?before=&after= links and self-contained --embed-out static preview bundles.

For local development inside the docs site, run pnpm --filter forge-docs dev and open http://localhost:4321/playground/. For standalone playground development, run pnpm --filter forge-playground dev (http://127.0.0.1:8787, or pass FORGE_OPENAPI_SPEC=./my-spec.json for a custom baseline).

…ink flows

Adds an interactive in-browser CLI dry-run sandbox for the generated `cf` plugin (with argument parsing, validation, confirmation-gate simulation, curl synthesis, jq output filtering, and tab completion), expands the static link/preview encoder (`scripts/encode-link.mjs`), adds package documentation, and fixes bugs across the Rust/WASM patch engine, UI editor, custom TS plugin runner, and TypeScript scratchpad.
The WASM patcher previously missed RFC 6901 JSON Pointer unescaping/escaping when matching or rewriting `$ref` targets across paths and schemas, dropped root-level CLI commands from the catalog, and risked overwriting shared arena buffers when custom TS plugins computed baseline diffs after a patched run. The patcher now unescapes and re-escapes pointer segments uniformly across all OpenAPI component sections, isolates cached baseline diagnostics per plugin, and evaluates custom plugin outputs before re-running WASM against the baseline.
On the UI side, the OpenAPI editor and TS/CLI sandboxes now handle YAML/JSON toggling, standalone and custom-baseline error highlighting, YAML list-item and mid-token autocomplete without leaving trailing suffixes, root-module selection in the TS scratchpad, explicit `--no-*` boolean flag parsing without shadowing positive flags, and narrow-viewport header wrapping without clipping controls.
Runs cargo fmt across packages/forge-playground Rust sources and updates packages/forge-playground/Cargo.lock after rebasing onto origin/main (cloudflare-forge 0.4.0).
@github-actions

This comment was marked as outdated.

@pkg-pr-new

pkg-pr-new Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
npm i https://pkg.pr.new/cloudflare/forge/@cloudflare/forge@195

commit: 832bff6

teamchong and others added 13 commits November 30, 2026 11:33
…ine release fallback

Custom TS/JS plugin source is no longer serialized into or restored from URL hash (#s=...) or embedded initial state, preventing shared links from executing arbitrary plugin code on load and resolving the CodeQL js/code-injection alert.
Also updates scripts/build.mjs and the playground workflows so baseline fetching falls back to the latest GitHub release carrying openapi.forge.json when GitHub's latest release is a CLI tag (such as forge@0.4.0) without that asset.
Replaces the unconfirmed cf-forge.workers.dev URL in the playground README with a generic <playground-host> placeholder and updates DEFAULT_PLAYGROUND_URL in scripts/encode-link.mjs to the temporary cf-api-docs.workers.dev workers.dev default until a custom domain is configured.
Removes the hardcoded workers.dev URL from DEFAULT_PLAYGROUND_URL in encode-link.mjs so callers default to the local dev server (http://127.0.0.1:8787/) and pass --base-url or FORGE_PLAYGROUND_URL for a deployed instance.
…y workflows

Removes `.github/workflows/preview-playground.yml` and reverts the playground deploy step in `.github/workflows/deploy-docs.yml` so PR #195 does not use the `cf-api-docs` Cloudflare secrets (`CLOUDFLARE_ACCOUNT_ID` / `CLOUDFLARE_API_TOKEN`) or deploy PR previews via GitHub Actions.
Follows up on documentation review feedback from #115 across the Forge docs site:

- Centralize current vs. future input support in a new `Input support` page (`start/input-support.mdx`) and frame the pipeline, model, plugins, targets, and `parse` guide around Forge's shared API model rather than tying plugins to OpenAPI.
- Update adoption and naming guidance to recommend `x-forge-group-name` and `x-forge-method-name` before changing `operationId`, clarify compatibility-mode normalization, deduplicate `x-forge-skip` in the extensions reference, and link to `x-forge-property-name`.
- Switch installation and CI examples to the published `@cloudflare/forge` npm package while retaining `pkg.pr.new` instructions for preview builds.
- Refine plugin, CLI, and TypeScript target docs (trim duplicated field lists in favor of the plugin API reference, clarify sync `generate`, root output files, and `forge inspect methods` `availability`).
…198)

Instructs agents to run pnpm format/check after any non-Rust edit (including Markdown, JSON, YAML, and TOML) and just fmt/lint after any Rust edit.
Align Forge documentation with the Cloudflare style guide while preserving precise technical guidance. Update page structure, headings, descriptions, terminology, accessibility, contributor guidance, and compatibility documentation.
…ional spec (#208)

* feat(cli): accept `--input`/`-i` on `forge generate`, deprecate positional

`forge generate openapi.json --target ts --out sdk` reads ambiguously:
`openapi.json` looks like an output of `generate`, not its input. Add
`--input <SPEC>` (short form `-i`) to name the OpenAPI document
explicitly, matching the convention `openapi-generator` and
`swagger-codegen` already use.

The positional `<SPEC>` still works for backwards compatibility, but
prints a one-line deprecation warning on stderr pointing at `--input`,
and will be removed in a future release.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore: apply oxfmt to dependabot.yml

`pnpm format:check` was failing on `.github/dependabot.yml` because the
file was committed before the rest of the tree was reformatted. Run
`pnpm format` on it so CI's format check passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
ematipico and others added 2 commits December 3, 2026 10:46
Mount the Forge Web Playground inside `packages/docs` at `/playground/` sharing the Nimbus `BaseLayout`, Furnace light and dark tokens, and `ClientRouter` navigation, with top-left `Docs` and `Playground` header tabs next to the Forge lockup and no docs sidebar on the playground route.

`packages/docs` build and dev scripts now run `packages/forge-playground/scripts/build.mjs --sync-docs` before `cf dev` and `cf build` so Workers Builds previews, production deploys, and CI link checks bundle the compiled WASM module, TypeScript worker bundle, and compressed OpenAPI baseline under `public/playground/`, while standalone `forge-playground` dev (`8787`) keeps working unchanged.
@teamchong teamchong changed the title feat(playground): add Forge Web Playground feat(playground): add Forge Web Playground and embed in forge-docs Dec 3, 2026
…ink flows

Adds an interactive in-browser CLI dry-run sandbox for the generated `cf` plugin (with argument parsing, validation, confirmation-gate simulation, curl synthesis, jq output filtering, and tab completion), expands the static link/preview encoder (`scripts/encode-link.mjs`), adds package documentation, and fixes bugs across the Rust/WASM patch engine, UI editor, custom TS plugin runner, and TypeScript scratchpad.
The WASM patcher previously missed RFC 6901 JSON Pointer unescaping/escaping when matching or rewriting `$ref` targets across paths and schemas, dropped root-level CLI commands from the catalog, and risked overwriting shared arena buffers when custom TS plugins computed baseline diffs after a patched run. The patcher now unescapes and re-escapes pointer segments uniformly across all OpenAPI component sections, isolates cached baseline diagnostics per plugin, and evaluates custom plugin outputs before re-running WASM against the baseline.
On the UI side, the OpenAPI editor and TS/CLI sandboxes now handle YAML/JSON toggling, standalone and custom-baseline error highlighting, YAML list-item and mid-token autocomplete without leaving trailing suffixes, root-module selection in the TS scratchpad, explicit `--no-*` boolean flag parsing without shadowing positive flags, and narrow-viewport header wrapping without clipping controls.
Runs cargo fmt across packages/forge-playground Rust sources and updates packages/forge-playground/Cargo.lock after rebasing onto origin/main (cloudflare-forge 0.4.0).
…ine release fallback

Custom TS/JS plugin source is no longer serialized into or restored from URL hash (#s=...) or embedded initial state, preventing shared links from executing arbitrary plugin code on load and resolving the CodeQL js/code-injection alert.
Also updates scripts/build.mjs and the playground workflows so baseline fetching falls back to the latest GitHub release carrying openapi.forge.json when GitHub's latest release is a CLI tag (such as forge@0.4.0) without that asset.
Replaces the unconfirmed cf-forge.workers.dev URL in the playground README with a generic <playground-host> placeholder and updates DEFAULT_PLAYGROUND_URL in scripts/encode-link.mjs to the temporary cf-api-docs.workers.dev workers.dev default until a custom domain is configured.
Removes the hardcoded workers.dev URL from DEFAULT_PLAYGROUND_URL in encode-link.mjs so callers default to the local dev server (http://127.0.0.1:8787/) and pass --base-url or FORGE_PLAYGROUND_URL for a deployed instance.
…y workflows

Removes `.github/workflows/preview-playground.yml` and reverts the playground deploy step in `.github/workflows/deploy-docs.yml` so PR #195 does not use the `cf-api-docs` Cloudflare secrets (`CLOUDFLARE_ACCOUNT_ID` / `CLOUDFLARE_API_TOKEN`) or deploy PR previews via GitHub Actions.
Mount the Forge Web Playground inside `packages/docs` at `/playground/` sharing the Nimbus `BaseLayout`, Furnace light and dark tokens, and `ClientRouter` navigation, with top-left `Docs` and `Playground` header tabs next to the Forge lockup and no docs sidebar on the playground route.

`packages/docs` build and dev scripts now run `packages/forge-playground/scripts/build.mjs --sync-docs` before `cf dev` and `cf build` so Workers Builds previews, production deploys, and CI link checks bundle the compiled WASM module, TypeScript worker bundle, and compressed OpenAPI baseline under `public/playground/`, while standalone `forge-playground` dev (`8787`) keeps working unchanged.
Encode and expose `x-*` extensions across `ForgeInfo`, `ModelInfo`, `FieldInfo`, `BodyInfo`, `ResponseInfo`, and `ContentInfo` in the flat binary arena (`arena.rs` / `arena_host.ts`) to match the `forge:plugin@0.6.0` WIT interface from #187.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Cloudflare builds and deploys previews for this pull request. Learn more about Cloudflare previews.

Worker Status Deployment Commit
forge-docs Deployed Preview 832bff6

Updated: Dec 5, 2026, 22:50 UTC | Dashboard

Run packages/forge-playground/scripts/build.mjs --sync-docs from an Astro
astro:build:start integration in packages/docs/astro.config.ts so both
cf previews deploy and cf build generate and bundle public/playground/
assets before Astro emits the site.
Remove transition:name="nb-content" from playground.astro's full-bleed <main> and call event.viewTransition.skipTransition() on astro:before-swap when crossing between Docs and /playground/, preventing the browser from morphing the centered docs column into the full-width playground while preserving normal Docs-to-Docs transitions.
…e fallback

Switch the playground build script from the retired openapi.forge.json release asset to cloudflare/api-schemas/main/openapi.json with ETag caching so the bundled openapi.baseline.json.gz fallback stays fresh across builds.

Load cloudflare/api-schemas/main/openapi.json live at runtime first (10s timeout) and fall back automatically to the build-time snapshot when offline, blocked, or if the live schema fails to parse.
…plete and ViewTransition

Replace the Try cf CLI toolbar Copy curl button with Copy command so users can copy the composed cf command directly regardless of --help or group commands, and move Copy curl inline onto the Equivalent curl block in the dry-run card.

Also fix three UX bugs found while dogfooding:
- Move cursor to the end and append a trailing space when clicking Autocomplete on a blurred/complete token so flag and subcommand suggestions open on the first click.
- Wrap --help output cleanly and add .btn.active and .btn:disabled styles so toggle and disabled states are visible.
- Catch the rejected ViewTransition.ready promise in Header.astro when calling skipTransition() across Docs and Playground.
…m arena

Move all Forge WASM baseline indexing, OpenAPI patching, node extraction, and
SDK generation into a dedicated Web Worker with zero-copy ArrayBuffer transfers
and single-slot patch coalescing, minify playground JS and CSS bundles in
build.mjs, and add preconnect/preload hints plus IndexedDB
stale-while-revalidate caching for the live Cloudflare api-schemas baseline.

Previously, parsing and diffing the 28.78 MB baseline ran synchronously on the
main thread, buffered full-document serde_json::Value trees, and packed Forge
AST tables even for plugins that never read them. Streaming JSON normalization
directly into Forge::parse, using Arc<RawValue> with a custom map visitor on
FastOpenApiDoc, skipping unused AST tables in arena v3, caching negative plugin
diagnostics alongside compiled arenas, and parking the Cloudflare baseline
across Standalone mode switches cuts peak WASM memory and eliminates
main-thread freezes.
…e TS VFS

Offload custom TypeScript plugin execution and diff packing to the Web Worker, virtualize code and diff tables over 350 rows alongside progressive file-tree rendering, cache OpenAPI patch gutter and backdrop bands across keystrokes, and switch the TypeScript scratchpad language service to lazy file readers with per-file incremental snapshot caching across edits.

Large Cloudflare OpenAPI baselines and patches previously stalled the UI thread because custom plugins executed synchronously on the main thread, the patch editor rebuilt thousands of line backdrop elements and re-parsed the full spec on every keystroke, full-file viewers inserted thousands of table rows at once, and entering the TypeScript scratchpad eagerly decoded and re-parsed every generated SDK file. Pre-transpiling custom plugins when the browser compiler is loaded lets the worker execute them off-thread and return a single packed UTF-8 buffer for lazy decoding, while spacer-bounded table windowing, contiguous backdrop range bands, and generation-keyed virtual file snapshots keep main-thread interactions responsive.
Dedicated Web Worker message events carry an empty origin string and a null source, while cross-document postMessage events populate source and set origin to the sender origin.

CodeQL models any unguarded onmessage handler as a remote postMessage source, flagging custom TypeScript plugin execution inside wasm_worker.ts as js/code-injection after moving plugin evaluation off the main thread. Reject messages with a non-null source or an origin outside the empty worker origin and self.location.origin before reading ev.data.
… on missing SDK extensions

Pre-existing normalized schema name collisions in the full upstream baseline (for example, two schemas whose names normalize identically) previously caused baseline compilation and every patched run against that baseline to fail with zero generated files. Baseline loading now disambiguates colliding upstream schemas in the normalized doc via a synthetic x-forge-model-name while keeping the raw schema map intact so user patches are still checked for new conflicts, and falls back to standalone compilation when an upstream baseline still fails to compile for an unrelated reason.

When a valid OpenAPI spec has paths but generates zero SDK/CLI changes or methods without Forge/Stainless/Fern extensions, the Playground now emits an informational NO_SDK_EXTENSIONS diagnostic explaining how to annotate operations.
…fetch errors

OpenAPI 3.x discriminator.mapping values and discriminator.defaultMapping can reference schemas either as #/components/schemas/<Name> pointers or as bare schema names. Previously the service-bundle patcher, ref collectors, and unresolved-ref checker only traversed $ref keys, so prefixed bundles with discriminators failed linking with UNRESOLVED_SCHEMA_REF and minimal patches dropped discriminator-only target schemas.

Mirrors Forge's linker target handling across patch.rs (collect_schema_refs, rewrite_bundle_schema_refs, check_unresolved_refs, unprefix_schema_refs), ui/app.ts, and scripts/encode-link.mjs, raises DEFAULT_MAX_URL_LENGTH to 48,000 so larger diffs stay inline in #s= without hitting cross-origin raw URL fetches, and clarifies browser CORS/private-repo fetch errors when ?before=&url= or ?url= fails.
Acquire ENGINE_TEST_LOCK in test_round14_discriminator_mapping_and_default_mapping_rewriting so parallel cargo test runs cannot race on the global WASM engine state (fixing the GitHub CI flake).

Also gate discriminator-object handling on a string propertyName across patch.rs, ui/app.ts, and encode-link.mjs so schema properties literally named "discriminator" still recurse for $ref collection, prefix rewriting, unprefixing, and unresolved-ref diagnostics.
…atches

Supersede combined account-or-zone baseline routes when a service bundle
patches a concrete account or zone path with the same HTTP method and SDK
method route, resolve separator-agnostic prefixed schema keys, and isolate
pre-existing baseline schema collisions regardless of which plugin loads
first. Partial OpenAPI patches also retain info, components.pathItems, and
$ref sibling overrides during inlining, while URL delta encoding bounds
line-LCS rename pairing, includes OpenAPI 3.2 HTTP methods, and aligns
try-ts and try-cli views with their target plugin.

Published public baselines merge matching account and zone operations into a
synthetic combined route and mark the originals skipped, and some bundles
join schema prefixes with hyphens while the baseline uses underscores, so
patching a service bundle without superseding or separator-tolerant lookup
produced false method and schema conflicts. In the cf CLI sandbox and
catalog, intersection enum choices now surface on options, union body
variants keep variant-only flags optional, and multipart or non-JSON bodies
stop colliding with JSON-parsed --body overrides.
…fallbacks

Align service-bundle patching with live OpenAPI bundle conventions across the Rust/WASM linker, URL encoder, and web UI:

- Prefix service-bundle schemas unconditionally in additive mode and use two-pass exact-claim-first prefixing (with separator-mismatch resolution) when patching existing baselines, avoiding false collisions when a schema already starts with the prefix or mixes `-` and `_`.
- Preserve asymmetric HTTP methods on merged account/zone twin routes, avoid clobbering active pre-combined operations when patching an ignored twin stub, restore pre-combination metadata when extracting a twin node, and keep un-skipped surviving twins in conflict checks.
- Preserve top-level spec metadata and support `x-forge-delete-commands`, `before`/`after` URL fallback on unsupported section edits, and twin subpath preservation in minimal delta patches.
…dget

Only increment the inline expansion node budget when recursing inside an active $ref expansion (seen.size > 0), instead of counting every node visited across both top-level OpenAPI documents.
Counting top-level nodes penalized large bundles even when an edit only touched a small part of the document and expanded few or no component references, causing encode-link and the UI to exceed the budget prematurely.
…URL handling

Patch merging now preserves OpenAPI info and servers metadata, handles empty patches cleanly, strips pre-combined x-fern-ignore twin routes after deletion, and recurses into nested x-forge-commands groups with dotted x-forge-delete-commands paths (including literal dotted command keys). Non-additive bundle prefixing now uses two-pass case-insensitive schema prefixing, and cross-bundle mode applies x-public-prefix unconditionally even when a single schema hint is passed.

Schema ref inlining now skips literal OpenAPI value keys (default, const, enum, example, and named examples), expands components.pathItems, honors allowRefSiblingMeta strictly for OAS 3.1 summary and description overrides, and bounds total expansion work by node count rather than depth alone. In the web UI, malformed share hashes show an explicit error toast instead of silently loading the default baseline, share links strip stale query params, switching baselines resets stale scratchpad/worker state, and plugin auto-selection routes command-only patches to the CLI sandbox.
…nd quick bar rendering

Track parent OpenAPI map container keys when traversing schema trees for literal value key skipping, discriminator handling, ref rewriting, and ref inlining, and fix CLI sandbox group selection and quick-command bar rendering.

Previously, treating keys like default, example, enum, const, or discriminator as literal OpenAPI keywords regardless of parent key skipped real schema properties under map containers such as properties (for example a property literally named default pointing to a schema ref), causing missing transitive schemas in minimal patches and UNRESOLVED_SCHEMA_REF diagnostics during bundle rewriting. Tracking map container parents distinguishes schema property names from actual keyword values and skips JSON Schema 2020-12 literal examples arrays without treating their entries as refs.

In the web UI and CLI sandbox, root router files were selected ahead of modified service files and ignored patched API paths when resolving the initial CLI command group, falling back to the first alphabetical group instead of the patched service. Prioritize modified non-root service files and patched API paths during selection, and remove the stray closing template literal in renderCliSandboxView so quick-command chips render instead of raw JS text.
… and CLI Enter handling

Invalid YAML in the OpenAPI editor previously fell through to the Rust JSON parser and surfaced a misleading 'Invalid Replacement JSON' error. Catch YAML syntax errors in runCurrentPatchAsync, report a clickable YAML_PARSE_ERROR diagnostic with line extraction, and avoid sending unparsed YAML to WASM.

Clicking a diagnostic now focuses the OpenAPI editor and selects the offending line rather than only scrolling, and pressing Enter in the cf CLI sandbox executes and records history unless the user explicitly navigated the autocomplete menu with ArrowDown or ArrowUp.
…de on URL fetch error

When loading a custom baseline via ?baseline= or an inline baseline, the WASM engine emits a generic 'Full Baseline Loaded (Cloudflare api-schemas)' summary even though the active baseline is not Cloudflare. Normalize that summary to the active custom baseline label before rendering or formatting Markdown exports.

When ?url= or ?before=&url= fails to fetch without an explicit ?baseline=, the playground skips loading the Cloudflare baseline but left baselineMode set to 'cloudflare', leaving the header badge stuck on 'Baseline Unavailable' and the baseline dropdown out of sync. Reset baselineMode to 'none' and sync the baseline selector when no catalog is loaded so the header accurately reflects standalone mode and users can still switch to Cloudflare.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants