-
-
Notifications
You must be signed in to change notification settings - Fork 3k
chore(admin): typesafe API client + TanStack Query rails (#7638) #7695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JohnMcLear
wants to merge
2
commits into
ether:develop
Choose a base branch
from
JohnMcLear:chore/admin-typesafe-api-7638-upstream
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,66 @@ | ||
| # React + TypeScript + Vite | ||
| # Admin UI | ||
|
|
||
| This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. | ||
| Vite + React 19 single-page app served at `/admin`. Talks to the backend over | ||
| socket.io for the existing settings / plugins / pads pages, and (when | ||
| endpoints are added to the OpenAPI spec) over a typed REST client. | ||
|
|
||
| Currently, two official plugins are available: | ||
| ## Scripts | ||
|
|
||
| - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh | ||
| - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh | ||
| | Script | What it does | | ||
| | -------------------- | -------------------------------------------------------- | | ||
| | `pnpm dev` | `gen:api` + Vite dev server (expects backend on :9001). | | ||
| | `pnpm gen:api` | Regenerates `src/api/{schema.d.ts,version.ts}` from the OpenAPI spec. | | ||
| | `pnpm build` | `gen:api` + `tsc` + `vite build`. | | ||
| | `pnpm build-copy` | Same, but writes into `../src/templates/admin`. | | ||
| | `pnpm test` | `gen:api` + smoke tests for the API client wiring. | | ||
| | `pnpm lint` | ESLint. | | ||
|
|
||
| ## Expanding the ESLint configuration | ||
| ## Typed API client | ||
|
|
||
| If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: | ||
| The admin uses [`openapi-typescript`] to generate types from | ||
| `src/node/hooks/express/openapi.ts`, [`openapi-fetch`] for typed requests, and | ||
| [`openapi-react-query`] for TanStack Query bindings. | ||
|
|
||
| - Configure the top-level `parserOptions` property like this: | ||
| [`openapi-typescript`]: https://github.com/openapi-ts/openapi-typescript | ||
| [`openapi-fetch`]: https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch | ||
| [`openapi-react-query`]: https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-react-query | ||
|
|
||
| ```js | ||
| export default { | ||
| // other rules... | ||
| parserOptions: { | ||
| ecmaVersion: 'latest', | ||
| sourceType: 'module', | ||
| project: ['./tsconfig.json', './tsconfig.node.json'], | ||
| tsconfigRootDir: __dirname, | ||
| }, | ||
| } | ||
| ### Generated files | ||
|
|
||
| `admin/src/api/schema.d.ts` and `admin/src/api/version.ts` are generated by | ||
| `gen:api` and gitignored — never commit them. They are produced by: | ||
|
|
||
| ```sh | ||
| pnpm --filter admin gen:api | ||
| ``` | ||
|
|
||
| `admin/scripts/gen-api.mjs` loads `src/node/hooks/express/openapi.ts`, calls | ||
| `generateDefinitionForVersion` for the latest API version, pipes the JSON | ||
| through `openapi-typescript` to produce `schema.d.ts`, and emits a runtime | ||
| constant `LATEST_API_VERSION` (read from `info.version` in the spec) to | ||
| `version.ts` so `client.ts` can build the right `/api/<version>/` baseUrl. | ||
|
|
||
| `gen:api` runs as the first step of `dev`, `build`, `build-copy`, and | ||
| `test`, so a fresh checkout produces the generated files automatically when | ||
| any of those scripts is invoked. After modifying any of the following, the | ||
| next `pnpm <dev|build|test>` will refresh the generated files; you can also | ||
| run `gen:api` directly: | ||
|
|
||
| - `src/node/hooks/express/openapi.ts` | ||
| - `src/node/handler/APIHandler.ts` (changes to `latestApiVersion`) | ||
| - the resource definitions referenced by `openapi.ts` | ||
|
|
||
| ### Using the client | ||
|
|
||
| ```tsx | ||
| import { $api } from './api/client'; | ||
|
|
||
| const SettingsPanel = () => { | ||
| const { data } = $api.useQuery('get', '/admin/settings'); // example | ||
| return <pre>{JSON.stringify(data, null, 2)}</pre>; | ||
| }; | ||
| ``` | ||
|
|
||
| - Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked` | ||
| - Optionally add `plugin:@typescript-eslint/stylistic-type-checked` | ||
| - Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list | ||
| The admin endpoints are not yet present in the OpenAPI spec — this client is | ||
| in place to support upcoming work (see issue #7638 follow-up). For now, it is | ||
| exercised only by the smoke test. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| // admin/scripts/dump-spec.ts | ||
| // | ||
| // Imports the OpenAPI spec builder from the etherpad source and writes the | ||
| // flat-style spec for the latest API version as JSON to the file path passed | ||
| // as argv[2]. Invoked by admin/scripts/gen-api.mjs via `tsx`. | ||
| // | ||
| // Why a file argument instead of stdout: importing `openapi.ts` triggers | ||
| // `Settings` init, which configures log4js to write INFO/WARN lines to | ||
| // stdout. Capturing stdout would mix logs with JSON. | ||
|
|
||
| import { writeFileSync } from 'node:fs'; | ||
| import path from 'node:path'; | ||
| import { fileURLToPath, pathToFileURL } from 'node:url'; | ||
|
|
||
| const outFile = process.argv[2]; | ||
| if (!outFile) { | ||
| process.stderr.write('Usage: tsx scripts/dump-spec.ts <output-path>\n'); | ||
| process.exit(2); | ||
| } | ||
|
|
||
| const here = path.dirname(fileURLToPath(import.meta.url)); | ||
| const repoRoot = path.resolve(here, '..', '..'); | ||
|
|
||
| const apiHandlerPath = path.join(repoRoot, 'src', 'node', 'handler', 'APIHandler.ts'); | ||
| const openapiPath = path.join(repoRoot, 'src', 'node', 'hooks', 'express', 'openapi.ts'); | ||
|
|
||
| // `openapi.ts` and `APIHandler.ts` use CommonJS-style `exports.*`. Under tsx's | ||
| // ESM dynamic import, the whole `module.exports` is exposed as `default`. | ||
| type ApiHandlerModule = { latestApiVersion: string }; | ||
| type OpenApiModule = { | ||
| generateDefinitionForVersion: (version: string, style?: string) => unknown; | ||
| APIPathStyle: { FLAT: string; REST: string }; | ||
| }; | ||
|
|
||
| const apiHandlerMod = await import(pathToFileURL(apiHandlerPath).href); | ||
| const openapiMod = await import(pathToFileURL(openapiPath).href); | ||
|
|
||
| const apiHandler = (apiHandlerMod.default ?? apiHandlerMod) as ApiHandlerModule; | ||
| const openapi = (openapiMod.default ?? openapiMod) as OpenApiModule; | ||
|
|
||
| const spec = openapi.generateDefinitionForVersion( | ||
| apiHandler.latestApiVersion, | ||
| openapi.APIPathStyle.FLAT, | ||
| ); | ||
|
|
||
| writeFileSync(path.resolve(outFile), JSON.stringify(spec, null, 2), 'utf8'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| // admin/scripts/gen-api.mjs | ||
| // | ||
| // Regenerates admin/src/api/schema.d.ts from the live OpenAPI spec exported | ||
| // by src/node/hooks/express/openapi.ts. Run via `pnpm --filter admin gen:api`. | ||
|
|
||
| import { spawnSync } from 'node:child_process'; | ||
| import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs'; | ||
| import { tmpdir } from 'node:os'; | ||
| import path from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
|
|
||
| const here = path.dirname(fileURLToPath(import.meta.url)); | ||
| const adminRoot = path.resolve(here, '..'); | ||
| const outFile = path.join(adminRoot, 'src', 'api', 'schema.d.ts'); | ||
|
|
||
| const tmpDir = mkdtempSync(path.join(tmpdir(), 'etherpad-openapi-')); | ||
| const specPath = path.join(tmpDir, 'spec.json'); | ||
|
|
||
| // On Windows pnpm resolves to pnpm.cmd, which spawnSync can only find via a | ||
| // shell. Use shell on Windows only to avoid Node's DEP0190 warning elsewhere. | ||
| // Every argument here is fixed (no user input) so the shell:true variant is | ||
| // not an injection risk. | ||
| const spawnOpts = { | ||
| cwd: adminRoot, | ||
| stdio: 'inherit', | ||
| shell: process.platform === 'win32', | ||
| }; | ||
|
|
||
| try { | ||
| const dump = spawnSync( | ||
| 'pnpm', | ||
| ['exec', 'tsx', 'scripts/dump-spec.ts', specPath], | ||
| spawnOpts, | ||
| ); | ||
| if (dump.status !== 0) { | ||
| console.error(`dump-spec.ts failed with exit code ${dump.status}`); | ||
| process.exit(dump.status ?? 1); | ||
| } | ||
|
|
||
| const gen = spawnSync( | ||
| 'pnpm', | ||
| ['exec', 'openapi-typescript', specPath, '-o', outFile], | ||
| spawnOpts, | ||
| ); | ||
|
Comment on lines
+16
to
+44
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 3. Windows gen:api arg splitting admin/scripts/gen-api.mjs uses shell: true on Windows while passing file paths (tmpdir + repo paths) as arguments; if those paths contain spaces (common in Windows user temp dirs), cmd.exe tokenization can break the pnpm exec ... <path> calls and make pnpm gen:api fail. Agent Prompt
|
||
| if (gen.status !== 0) { | ||
| console.error(`openapi-typescript failed with exit code ${gen.status}`); | ||
| process.exit(gen.status ?? 1); | ||
| } | ||
|
|
||
| const header = | ||
| `// GENERATED — do not edit. Run \`pnpm --filter admin gen:api\` to regenerate.\n` + | ||
| `// Source: src/node/hooks/express/openapi.ts (#7638)\n\n`; | ||
| const body = readFileSync(outFile, 'utf8'); | ||
| writeFileSync(outFile, header + body, 'utf8'); | ||
|
|
||
| // Emit a runtime-side version constant so client.ts can build the right | ||
| // baseUrl. Generated paths are unprefixed (e.g. "/createGroup"), but the | ||
| // backend mounts the FLAT-style spec under /api/<version>/. | ||
| const spec = JSON.parse(readFileSync(specPath, 'utf8')); | ||
| const apiVersion = spec?.info?.version; | ||
| if (typeof apiVersion !== 'string' || apiVersion.length === 0) { | ||
| console.error('OpenAPI spec is missing info.version; cannot emit version.ts'); | ||
| process.exit(1); | ||
| } | ||
| const versionFile = path.join(adminRoot, 'src', 'api', 'version.ts'); | ||
| writeFileSync( | ||
| versionFile, | ||
| header + | ||
| `export const LATEST_API_VERSION = ${JSON.stringify(apiVersion)};\n` + | ||
| `export const API_BASE_URL = \`/api/\${LATEST_API_VERSION}\`;\n`, | ||
| 'utf8', | ||
| ); | ||
|
|
||
| console.log(`Wrote ${path.relative(process.cwd(), outFile)}`); | ||
| console.log(`Wrote ${path.relative(process.cwd(), versionFile)}`); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true, force: true }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| // admin/src/api/QueryProvider.tsx | ||
| // | ||
| // TanStack Query provider for the admin UI. Devtools are loaded lazily and | ||
| // only in dev builds so they don't ship to production. | ||
|
|
||
| import { lazy, Suspense, useState, type ReactNode } from 'react'; | ||
| import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; | ||
|
|
||
| const Devtools = import.meta.env.DEV | ||
| ? lazy(() => | ||
| import('@tanstack/react-query-devtools').then((m) => ({ | ||
| default: m.ReactQueryDevtools, | ||
| })), | ||
| ) | ||
| : null; | ||
|
|
||
| export const QueryProvider = ({ children }: { children: ReactNode }) => { | ||
| const [client] = useState( | ||
| () => | ||
| new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { | ||
| staleTime: 30_000, | ||
| refetchOnWindowFocus: true, | ||
| }, | ||
| }, | ||
| }), | ||
| ); | ||
|
|
||
| return ( | ||
| <QueryClientProvider client={client}> | ||
| {children} | ||
| {Devtools && ( | ||
| <Suspense fallback={null}> | ||
| <Devtools initialIsOpen={false} /> | ||
| </Suspense> | ||
| )} | ||
| </QueryClientProvider> | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // admin/src/api/__tests__/client.test.ts | ||
| // | ||
| // Smoke test that the OpenAPI client module loads and exposes the expected | ||
| // surface. Catches toolchain wiring regressions (missing peer deps, | ||
| // generator output that doesn't export `paths`, etc.). | ||
|
|
||
| import { test } from 'node:test'; | ||
| import assert from 'node:assert/strict'; | ||
|
|
||
| test('client module exports fetchClient and $api', async () => { | ||
| const mod = await import('../client.ts'); | ||
| assert.ok(mod.fetchClient, 'fetchClient export is present'); | ||
| assert.ok(mod.$api, '$api export is present'); | ||
| assert.equal(typeof mod.fetchClient.GET, 'function', 'fetchClient.GET is a function'); | ||
| assert.equal(typeof mod.$api.useQuery, 'function', '$api.useQuery is a function'); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| // admin/src/api/client.ts | ||
| // | ||
| // Typed HTTP client and TanStack Query hooks derived from the generated | ||
| // OpenAPI schema. Regenerate the schema with `pnpm --filter admin gen:api`. | ||
|
|
||
| import createClient from 'openapi-fetch'; | ||
| import createQueryHooks from 'openapi-react-query'; | ||
| import type { paths } from './schema'; | ||
| import { API_BASE_URL } from './version'; | ||
|
|
||
| export const fetchClient = createClient<paths>({ baseUrl: API_BASE_URL }); | ||
| export const $api = createQueryHooks(fetchClient); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1. schema.d.ts missing /admin-auth paths
📎 Requirement gap≡ CorrectnessAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools