Repository navigation
Add psl-playground: browser PSL editor wired to the language server - #856
Conversation
…rver Add a private apps/lsp-playground package providing the `psl-playground` binary. It opens a .psl file in a browser CodeMirror 6 editor wired to `prisma-next lsp --stdio` over a WebSocket bridge (vscode-ws-jsonrpc), publishing live PSL parse diagnostics. Config resolution: --config, else the nearest prisma-next.config.ts walking up from the schema, else a generated default-postgres config pointing prismaContract at the schema. Without any config, a default Postgres setup is assumed. Lives under apps/ (exempt from lint:deps layering); runs via tsx, no build step. Validated end-to-end: a broken schema yields PSL_UNTERMINATED_BLOCK through the full WS -> bridge -> stdio server -> publishDiagnostics chain. Signed-off-by: Serhii Tatarintsev <[email protected]>
Replace the separate Vite (5273) and bridge (30100) HTTP servers with one shared http.Server: Vite runs in middleware mode with its HMR socket bound to that server, and the bridge attaches an upgrade listener that only claims the /psl path. The client derives its WebSocket URL from window.location, so the editor and the language server share one origin/port (5273). attachBridge now takes an existing server instead of owning a port; the generated client runtime exports wsPath instead of a hard-coded wsUrl. Validated end-to-end on the single port: GET / -> 200 and ws://localhost:5273/psl yields PSL_UNTERMINATED_BLOCK for a broken schema. Signed-off-by: Serhii Tatarintsev <[email protected]>
…server The binary now runs with no schema argument: it stages a writable scratch schema under .playground/ and assumes a generated default-postgres config, matching the intended "without the config, assume default postgres" behaviour. A non-existent path is treated the same way; an existing file with no project config is staged as a sandbox copy under default-postgres. Adapt to the merged prisma-next lsp (PR #852), which dropped --config and now discovers each document config by walking up from the document path. The bridge no longer passes --config; instead the schema is staged into .playground/ beside its generated config so the walk-up finds it and the config @prisma-next imports resolve. An existing file already inside a project opens in place under its own discovered config. Validated against rebased origin/main: no-arg and existing-file launches both serve the editor on port 5273 and publish PSL_UNTERMINATED_BLOCK live. Signed-off-by: Serhii Tatarintsev <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a new ChangesLSP Playground App
Sequence DiagramsequenceDiagram
participant User
participant CLI as psl-playground (cli.ts)
participant Config as Config Resolvers
participant HTTP as HTTP Server
participant Vite as Vite Dev Server
participant Browser
participant Bridge as WS-LSP Bridge
participant LSP as prisma-next lsp --stdio
User->>CLI: psl-playground [schema.psl]
CLI->>Config: findNearestConfig(schemaPath)
alt no config found
Config->>Config: generateDefaultPostgresConfig → .playground/
end
CLI->>CLI: write src/client/runtime.ts (URIs + schema text)
CLI->>Vite: createServer (middleware mode, bound to HTTP)
CLI->>Bridge: attachBridge(HTTP, { path: "/psl" })
CLI->>HTTP: listen :5273
Browser->>HTTP: GET /
HTTP->>Vite: middleware handles request
Vite-->>Browser: index.html + client/main.ts bundle
Browser->>Bridge: WebSocket upgrade /psl
Bridge->>LSP: spawn node cli.js lsp --stdio
Browser->>Bridge: LSP initialize (JSON-RPC over WS)
Bridge->>LSP: forward via stdin
LSP-->>Bridge: LSP response via stdout
Bridge-->>Browser: forward JSON-RPC response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
size-limit report 📦
|
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (3)
apps/lsp-playground/src/cli.ts (1)
3-3: ⚡ Quick winUse
patheinstead ofnode:pathfor repo consistency.This file currently imports path helpers from
node:path; repo convention in TS tooling files preferspathe.Small consistency refactor
-import { basename, dirname, isAbsolute, resolve } from 'node:path'; +import { basename, dirname, isAbsolute, resolve } from 'pathe';Based on learnings: in this repo, TypeScript files should prefer
patheover Node’s built-innode:pathfor path operations.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/lsp-playground/src/cli.ts` at line 3, Replace the import statement that imports basename, dirname, isAbsolute, and resolve from node:path with an equivalent import from the pathe package instead. Update the import line at the top of cli.ts to maintain the same destructured exports but source them from pathe rather than node:path, ensuring consistency with the repository's TypeScript tooling conventions.Source: Learnings
apps/lsp-playground/src/default-config.ts (1)
2-2: ⚡ Quick winUse
pathehere as well for path operations.Line 2 should align with the repo convention and import from
patheinstead ofnode:path.Based on learnings: “In the Prisma-next repository, prefer importing and using
patheover the built-innode:pathmodule for path operations across the codebase.”Suggested fix
-import { dirname, join } from 'node:path'; +import { dirname, join } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/lsp-playground/src/default-config.ts` at line 2, The import statement on line 2 is using the built-in node:path module instead of following the repository convention. Replace the import source from 'node:path' to 'pathe' while keeping the imported functions (dirname and join) the same. This aligns with the established pattern of using pathe for path operations throughout the codebase.Source: Learnings
apps/lsp-playground/src/find-config.ts (1)
2-2: ⚡ Quick winUse
patheinstead ofnode:pathfor repo consistency.Please switch the Line 2 import to
patheto match the repository’s TS path-handling convention.Based on learnings: “In the Prisma-next repository, prefer importing and using
patheover the built-innode:pathmodule for path operations across the codebase.”Suggested fix
-import { dirname, join, parse } from 'node:path'; +import { dirname, join, parse } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/lsp-playground/src/find-config.ts` at line 2, Replace the import source in the find-config.ts file from 'node:path' to 'pathe' on the line that imports dirname, join, and parse. This ensures consistency with the repository's established convention of using the pathe module for path operations instead of the built-in node:path module. Keep the same destructured imports (dirname, join, parse) unchanged.Source: Learnings
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/lsp-playground/README.md`:
- Around line 50-53: The fenced code block containing the CodeMirror 6
architecture diagram is missing a language tag, which triggers the MD040 linting
rule. Add a language identifier to the opening fence of this code block by
changing the opening three backticks to include a language specifier (e.g.,
```text) instead of leaving it blank, to ensure the documentation passes lint
checks.
In `@apps/lsp-playground/src/bridge.ts`:
- Around line 46-50: The send method's webSocket.send callback throws errors
directly, which can cause uncaught exceptions and crash the process. Instead of
throwing the error in the callback when error is not null and not undefined,
handle it gracefully by closing or disposing of the WebSocket connection.
Replace the throw statement with appropriate error handling logic that
terminates the connection safely.
- Around line 77-79: When serverConnection is undefined (indicating
createServerProcess failed), the code currently returns silently, leaving the
WebSocket connection open with no backend and no feedback to the client. Instead
of the silent return, close the WebSocket connection (via the ws object) and log
a clear error message about the subprocess creation failure to provide explicit
feedback before returning. This prevents hanging clients and surfaces the actual
failure to aid debugging.
In `@apps/lsp-playground/src/cli.ts`:
- Around line 56-57: The `--config` argument parsing in the cli.ts file lacks
proper validation and enforcement. Add validation checks to ensure that when the
--config flag is present, it has an actual value provided after it (not
undefined or missing), and that the specified config path exists on the
filesystem. Additionally, ensure this explicit config is actually passed through
to the LSP process initialization instead of only affecting local configPath and
rootUri, or alternatively, add clear error handling that fails fast if the
config requirements cannot be met. Review the explicit config usage across all
referenced locations (lines around 87-98 and 167) to ensure consistency.
In `@apps/lsp-playground/src/client/main.ts`:
- Around line 14-16: The wsUrl variable assignment uses a bare `as` cast to
assert the type as the WebSocket URL union type (ws://${string} |
wss://${string}), which violates the production code typing guidelines. Replace
this bare `as` cast with the repo-approved cast helper function, either
`blindCast<T, "Reason">` or `castAs<T>`, ensuring you provide the appropriate
reason or context for the cast where required by the helper.
In `@apps/lsp-playground/tsconfig.json`:
- Around line 1-11: The outDir in the compilerOptions of tsconfig.json is set to
"dist" but should be changed to "dist-tsc" to align with the monorepo convention
established in the base tsconfig. Additionally, update the .gitignore file to
exclude "dist-tsc" instead of "dist", and update the clean script in
package.json to remove the "dist-tsc" directory instead of "dist" to maintain
consistency with the monorepo standard for output directories across all
packages.
---
Nitpick comments:
In `@apps/lsp-playground/src/cli.ts`:
- Line 3: Replace the import statement that imports basename, dirname,
isAbsolute, and resolve from node:path with an equivalent import from the pathe
package instead. Update the import line at the top of cli.ts to maintain the
same destructured exports but source them from pathe rather than node:path,
ensuring consistency with the repository's TypeScript tooling conventions.
In `@apps/lsp-playground/src/default-config.ts`:
- Line 2: The import statement on line 2 is using the built-in node:path module
instead of following the repository convention. Replace the import source from
'node:path' to 'pathe' while keeping the imported functions (dirname and join)
the same. This aligns with the established pattern of using pathe for path
operations throughout the codebase.
In `@apps/lsp-playground/src/find-config.ts`:
- Line 2: Replace the import source in the find-config.ts file from 'node:path'
to 'pathe' on the line that imports dirname, join, and parse. This ensures
consistency with the repository's established convention of using the pathe
module for path operations instead of the built-in node:path module. Keep the
same destructured imports (dirname, join, parse) unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 590afa88-13d4-4712-ac94-58daf58b0b19
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (12)
apps/lsp-playground/.gitignoreapps/lsp-playground/README.mdapps/lsp-playground/bin/psl-playground.mjsapps/lsp-playground/fixtures/broken.pslapps/lsp-playground/index.htmlapps/lsp-playground/package.jsonapps/lsp-playground/src/bridge.tsapps/lsp-playground/src/cli.tsapps/lsp-playground/src/client/main.tsapps/lsp-playground/src/default-config.tsapps/lsp-playground/src/find-config.tsapps/lsp-playground/tsconfig.json
Three CI failures on the PR, fixed:
- Type Check: the generated client runtime module was gitignored, so a fresh
checkout could not resolve `./runtime` and tsc failed. Commit a neutral
placeholder runtime.ts (still overwritten at launch) and stop ignoring it.
- Lint cast ratchet: the no-bare-cast plugin flagged three sites. Two were
false positives on `import { createServer as X }` aliases — rewritten as
namespace imports (`import * as nodeHttp` / `import * as vite`). The third
was a real `as` on the WebSocket URL; rebuilt so each protocol branch is
already the correct template-literal type, eliminating the cast.
- Semgrep detect-insecure-websocket: false positive for a localhost-only dev
playground served over http (wss/TLS is meaningless on loopback; we already
upgrade to wss when served over https). Suppressed with a justified
nosemgrep comment.
Re-validated end-to-end: launches, serves on port 5273, publishes
PSL_UNTERMINATED_BLOCK; typecheck clean, lint exit 0, cast ratchet delta=0.
Signed-off-by: Serhii Tatarintsev <[email protected]>
The detect-insecure-websocket rule fires on every `ws://` token, including ones in comments and the type annotation, so the earlier single suppression left three findings. Keep the suppression local instead of excluding the rule repo-wide: remove `ws://` from comments and annotate the two real code lines (the client serverUri and the CLI bridge-URL log) with `// nosemgrep`. The scheme already mirrors the page origin (plain on http, secure on https); plain ws on localhost loopback is the expected, safe behaviour for this dev tool. typecheck clean, lint exit 0, cast ratchet delta=0, playground still serves. Signed-off-by: Serhii Tatarintsev <[email protected]>
- bridge: don't throw from the WebSocket send callback (a transient send error could crash the playground process); close the socket instead. - bridge: fail loud when the LSP subprocess can't be spawned — log a clear error and dispose the socket rather than leaving the client on a backend-less connection. - cli: drop the `--config` flag. The language server discovers config by walking up from each document's path and cannot be pointed at an arbitrary config, so accepting `--config` was misleading and non-functional. - tsconfig: stop overriding rootDir/outDir; inherit the base (dist-tsc). - README: tag the architecture fence as `text` (MD040) and drop the removed `--config` from the config-resolution docs. The stale CodeRabbit notes about the bare `as` cast and the unsuppressed Semgrep finding were already resolved in earlier commits. typecheck clean, lint exit 0, cast ratchet delta=0, playground still serves and publishes diagnostics. Signed-off-by: Serhii Tatarintsev <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/lsp-playground/src/cli.ts`:
- Around line 81-83: The condition at line 81 in the sourceFile validation only
checks if the path exists using fileExists() but does not verify that it is
actually a regular file and not a directory. This causes a crash later at line
114 when readFile() attempts to read a directory as a file. Enhance the
condition to also validate that sourceFile is a regular file (not just that it
exists) by adding an additional check before proceeding with
findNearestConfig(), ensuring the validation fails fast for directory paths.
- Line 56: The schemaArg assignment on line 56 silently ignores any unsupported
flags or extra positional arguments beyond the first non-flag token, which can
lead to unexpected behavior. After extracting schemaArg using the find method,
add explicit validation to check for unsupported flags (tokens starting with
`--` that are not recognized) and extra positional arguments (additional
non-flag tokens beyond the single schema argument). If any invalid flags or
extra positional arguments are detected, throw a usage error message that
clearly explains the valid command syntax instead of silently accepting the
malformed input.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: b2251150-04c4-4858-b8fc-5e8600b4fc4f
📒 Files selected for processing (4)
apps/lsp-playground/README.mdapps/lsp-playground/src/bridge.tsapps/lsp-playground/src/cli.tsapps/lsp-playground/tsconfig.json
✅ Files skipped from review due to trivial changes (2)
- apps/lsp-playground/tsconfig.json
- apps/lsp-playground/README.md
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/lsp-playground/src/bridge.ts
Address the second round of review: - Reject unknown flags and more than one positional argument with an explicit usage error, instead of silently picking the first non-flag token. - Fail fast when the schema path exists but is not a regular file (e.g. a directory), rather than crashing later in readFile. typecheck clean, lint exit 0, cast ratchet delta=0; edge cases (unknown flag, extra positional, directory path) now exit 1 with clear messages, happy path still serves. Signed-off-by: Serhii Tatarintsev <[email protected]>
Linked issue
n/a — small, self-contained dev tool. Builds on the language server from #852 (
prisma-next lsp).Summary
A private
apps/lsp-playgroundpackage providing thepsl-playgroundbinary: it opens a PSL file in a browser CodeMirror 6 editor wired toprisma-next lspover a single-port WebSocket bridge, giving you live PSL parse diagnostics without setting up an editor extension.At a glance
Then open
http://localhost:5273/and edit; diagnostics from@prisma-next/psl-parserupdate live. With no project config, the playground assumes a default-postgres setup.Decision
This ships one thing: a browser playground for the PSL language server, as a private
apps/package so it stays out of the framework build graph andlint:depslayering. Three design decisions shape it:codemirror-languageserverfor the editor (lighter than Monaco; grows into hover/completion as the server gains them).http.Server; the LSP WebSocket bridge attaches anupgradelistener that only claims/psl, so the editor, Vite HMR, and the language server all share port 5273.How it fits together
src/cli.tsresolves the schema and the config above it: an explicit--config+ file opens in place; an existing file inside a project opens in place under its discovered config; otherwise (no file / missing path / file with no project config) the schema is staged into.playground/and a default-postgres config is generated beside it..playground/(src/default-config.ts,stageSchemainsrc/cli.ts) is required because the language server discovers a document's config by walking up from the document's own path, and the generated config's@prisma-next/*imports must resolve through the workspacenode_modules.src/bridge.tsattaches to the shared server, and on each/pslconnection spawnsprisma-next lsp --stdioand forwards JSON-RPC viavscode-ws-jsonrpc(createServerProcess+forward).src/client/runtime.tshands the client the document URI, root, schema text, and WS path;src/client/main.tsmounts CodeMirror with thelanguageServerextension pointed at the same origin.Behavior changes & evidence
psl-playgroundwith no argument opens a scratch schema under default-postgres and publishes live diagnostics —apps/lsp-playground/src/cli.ts,apps/lsp-playground/src/default-config.ts. Validated manually end-to-end (no-arg launch →PSL_UNTERMINATED_BLOCK).psl-playground <file>opens an existing schema; if it has no project config it is staged as a sandbox copy under default-postgres, otherwise opened in place —apps/lsp-playground/src/cli.ts. Validated manually (staged-copy launch → diagnostics)./psl-scoped upgrade handler —apps/lsp-playground/src/cli.ts,apps/lsp-playground/src/bridge.ts.Reviewer notes
src/cli.ts— the arg parsing + schema/config resolution + single-port wiring live there. The branching in schema/config resolution is the part to spot-check..playground/rather than your original — both because the server needs the config's@prisma-next/*imports to resolve and because walk-up config discovery requires the schema to sit beside the generated config. This is intentional sandbox behaviour..playground/andsrc/client/runtime.tsare written at launch and excluded from git; only sources are tracked.@prisma-next/cli'sdist/cli.js) and the generated config loads built postgres-stack packages, so a fresh checkout needspnpm install+ a build of those packages before first run. Noted in the README.Compatibility / migration / risk
No framework surface changes.
apps/is exempt fromlint:deps; the package isprivateand unpublished. Zero risk to shipped code.Testing performed
pnpm --filter @prisma-next/lsp-playground typecheck— cleanpnpm --filter @prisma-next/lsp-playground lint— clean (exit 0)origin/main: no-arg launch and existing-file launch both serve the editor on port 5273 and publishPSL_UNTERMINATED_BLOCKfor a broken schema over the shared-port WebSocket bridge.Skill update
n/a — internal dev tool; no user-facing CLI/API/config surface of the framework changes (the
psl-playgroundbinary lives only in this private package).Alternatives considered
monaco-languageclient— heavier (pulls the vscode-api shims); CodeMirror 6 is lighter and sufficient for diagnostics, and grows into later language features.http.Serverto avoid hogging two ports.lsp-ws-proxy(Rust) or the 8-year-oldjsonrpc-ws-proxy—vscode-ws-jsonrpcis maintained, all-JS, andpnpm-installable.Checklist
git commit -s) per the DCO.TML-NNNN: <sentence-case title>form (n/a — no Linear ticket; self-contained dev tool).Summary by CodeRabbit
Release Notes
New Features
Documentation
Chores
Tests