Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ or provide the CA certs:

See [CONFIGURATION.md](CONFIGURATION.md) for complete configuration options.

### Running Standalone UI with mock data (no backend)

The standalone app can run fully offline using MSW and the existing Cypress fixtures.

```shell
npm run dev:mock
```

Notes:
- Mocked endpoints cover core `/api/flightctl/api/v1` routes (fleets, repositories) and can be extended in `apps/standalone/src/mocks/handlers.ts`.
- To disable mocks in the same session, stop the dev server and run `npm run dev` (without the `USE_MSW` flag).

### Running UI as OCP plugin

With this option, the Flight Control UI will run as a Plugin in the OCP console.
Expand Down
9 changes: 8 additions & 1 deletion apps/standalone/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"build": "NODE_ENV=production npm run ts-node ../../node_modules/.bin/webpack --mode=production",
"start-prod": "npm run ts-node ../../node_modules/.bin/webpack serve --mode=production --color --progress",
"dev": "concurrently \"npm run dev:proxy\" \"npm run dev:ui\"",
"dev:mock": "USE_MSW=true npm run dev",
"dev:kind": ". ./scripts/setup_env.sh && npm run dev",
Comment on lines +14 to 15

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

Align msw dependency with generated worker version

The dev:mock script and msw.workerDirectory config look good and line up with the new mock flow.

One thing to double‑check: apps/standalone/public/mockServiceWorker.js declares a PACKAGE_VERSION of 2.12.1, while this package pins msw to ^2.4.1. MSW uses an integrity check between the client library and the worker, so having different versions can cause warnings and, in worst cases, protocol mismatches.

To keep things in sync, consider either:

  • Bumping the devDependency to match the worker’s version (for example, to "msw": "^2.12.x" based on the worker file), and reinstalling; or
  • Pinning msw to your desired version and regenerating the worker with the matching CLI (npx msw@<version> init public --save).

That way the client and worker stay version-aligned.

Also applies to: 24-24, 63-68


🏁 Script executed:

#!/bin/bash
# Show the version constant in the worker and the msw devDependency side-by-side.

echo "Worker version constant:"
rg -n "PACKAGE_VERSION" apps/standalone/public/mockServiceWorker.js -n || echo "No PACKAGE_VERSION found"

echo
echo "msw devDependency in apps/standalone/package.json:"
rg -n '"msw"' apps/standalone/package.json -n || echo "No msw devDependency found"

Length of output: 196


Align msw dependency version with generated worker

The dev:mock script and msw.workerDirectory config are correctly set up.

However, verification confirms a version mismatch: the worker at apps/standalone/public/mockServiceWorker.js (line 10) declares PACKAGE_VERSION = '2.12.1', while apps/standalone/package.json (line 24) pins "msw": "^2.4.1". MSW's integrity check between client and worker can flag or fail on version mismatches.

Resolve by either:

  • Updating the devDependency to "msw": "^2.12.x" and reinstalling, or
  • Pinning to your desired version and regenerating the worker: npx msw@<version> init public --save
🤖 Prompt for AI Agents
In apps/standalone/package.json around lines 14-15 (and note line 24 where "msw"
is pinned) and apps/standalone/public/mockServiceWorker.js (line 10 showing
PACKAGE_VERSION = '2.12.1'), the MSW package version in package.json mismatches
the generated worker; update package.json to use a matching MSW version (e.g.,
set "msw": "^2.12.x") and run a reinstall (npm install/yarn) so lockfile
updates, or alternatively pin package.json to your desired version and
regenerate the worker with npx msw@<version> init public --save; finally commit
the updated package.json, lockfile, and the regenerated
public/mockServiceWorker.js.

"dev:proxy": "cd ../../proxy && nodemon --watch 'proxy/**/*' --exec 'go run' app.go --signal SIGTERM",
"dev:ui": "npm run ts-node ../../node_modules/.bin/webpack serve --mode=development --color --progress",
Expand All @@ -20,6 +21,7 @@
},
"devDependencies": {
"@types/react-dom": "^18.2.17",
"msw": "^2.4.1",
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.8.1",
"css-minimizer-webpack-plugin": "^5.0.1",
Expand Down Expand Up @@ -58,5 +60,10 @@
"react-i18next": "^11.7.3",
"react-router-dom": "^6.22.0",
"yup": "^1.3.3"
},
"msw": {
"workerDirectory": [
"public"
]
}
}
}
349 changes: 349 additions & 0 deletions apps/standalone/public/mockServiceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,349 @@
/* eslint-disable */
/* tslint:disable */

/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
*/

const PACKAGE_VERSION = '2.12.1'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()

addEventListener('install', function () {
self.skipWaiting()
})

addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})

addEventListener('message', async function (event) {
const clientId = Reflect.get(event.source || {}, 'id')

if (!clientId || !self.clients) {
return
}

const client = await self.clients.get(clientId)

if (!client) {
return
}

const allClients = await self.clients.matchAll({
type: 'window',
})

switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}

case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}

case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)

sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}

case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)

const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})

// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}

break
}
}
})

addEventListener('fetch', function (event) {
const requestInterceptedAt = Date.now()

// Bypass navigation requests.
if (event.request.mode === 'navigate') {
return
}

// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (
event.request.cache === 'only-if-cached' &&
event.request.mode !== 'same-origin'
) {
return
}

// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}

const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
})

/**
* @param {FetchEvent} event
* @param {string} requestId
* @param {number} requestInterceptedAt
*/
async function handleRequest(event, requestId, requestInterceptedAt) {
const client = await resolveMainClient(event)
const requestCloneForEvents = event.request.clone()
const response = await getResponse(
event,
client,
requestId,
requestInterceptedAt,
)

// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)

// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()

sendToClient(
client,
{
type: 'RESPONSE',
payload: {
isMockedResponse: IS_MOCKED_RESPONSE in response,
request: {
id: requestId,
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
)
}

return response
}

/**
* Resolve the main client for the given event.
* Client that issues a request doesn't necessarily equal the client
* that registered the worker. It's with the latter the worker should
* communicate with during the response resolving phase.
* @param {FetchEvent} event
* @returns {Promise<Client | undefined>}
*/
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)

if (activeClientIds.has(event.clientId)) {
return client
}

if (client?.frameType === 'top-level') {
return client
}

const allClients = await self.clients.matchAll({
type: 'window',
})

return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}

/**
* @param {FetchEvent} event
* @param {Client | undefined} client
* @param {string} requestId
* @param {number} requestInterceptedAt
* @returns {Promise<Response>}
*/
async function getResponse(event, client, requestId, requestInterceptedAt) {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = event.request.clone()

function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)

// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)

if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}

return fetch(requestClone, { headers })
}

// Bypass mocking when the client is not active.
if (!client) {
return passthrough()
}

// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return passthrough()
}

// Notify the client that a request has been intercepted.
const serializedRequest = await serializeRequest(event.request)
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
interceptedAt: requestInterceptedAt,
...serializedRequest,
},
},
[serializedRequest.body],
)

switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}

case 'PASSTHROUGH': {
return passthrough()
}
}

return passthrough()
}

/**
* @param {Client} client
* @param {any} message
* @param {Array<Transferable>} transferrables
* @returns {Promise<any>}
*/
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()

channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}

resolve(event.data)
}

client.postMessage(message, [
channel.port2,
...transferrables.filter(Boolean),
])
})
}

/**
* @param {Response} response
* @returns {Response}
*/
function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}

const mockedResponse = new Response(response.body, response)

Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})

return mockedResponse
}

/**
* @param {Request} request
*/
async function serializeRequest(request) {
return {
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.arrayBuffer(),
keepalive: request.keepalive,
}
}
Comment on lines +1 to +349

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

Treat this MSW worker file as the single source of truth

This looks like the standard mockServiceWorker.js generated by the MSW CLI (with integrity checks, message protocol, etc.), and it’s already annotated as “do NOT modify”.

Given that, it’s best to:

  • Keep this file entirely generated (regenerate via MSW CLI when upgrading msw), and
  • Ensure your bundling config (e.g., webpack.config.ts) copies this file when needed, rather than pulling in other MSW artifacts that might diverge from it.

That will keep the client and worker behavior consistent across environments.


🌐 Web query:

Check MSW's documentation on how `mockServiceWorker.js` is generated and kept in sync with the installed `msw` version, and whether it should be committed vs copied from `node_modules`.

💡 Result:

Short answer: MSW provides an init CLI that copies the packaged worker into your public dir (npx msw init <PUBLIC_DIR> --save). The docs recommend committing mockServiceWorker.js to Git so everyone uses the same worker, but also note you may treat it as a generated artifact and generate it automatically (CI/install step) if you prefer. The client accepts any worker within the same major MSW version, but MSW still recommends keeping the copied worker up-to-date with the installed msw and performs an integrity check (you can configure msw.workerDirectory). [1][2][3]

Key doc points:

  • How it’s produced: run npx msw init <PUBLIC_DIR> to copy the worker from the msw package into your app. [1][2]
  • Commit vs generated: recommended to commit mockServiceWorker.js to Git for team consistency; alternative is to generate it automatically as part of project setup/CI. [1][3]
  • Version/sync: the client can use a worker within the same major version, but MSW recommends keeping it in sync and runs an integrity check that may surface an “outdated Service Worker” message; use msw.workerDirectory if needed. [1][3]

Sources:

  • MSW “Managing the worker” / generating & updating the worker. [1]
  • MSW “Browser integration” / init command. [2]
  • MSW FAQ (Should I commit the worker script?). [3]


Align worker file handling with MSW's recommended practice

MSW's recommended approach is to commit mockServiceWorker.js to Git for team consistency, though treating it as a generated artifact and auto-generating it during CI/install is an alternative. The file should not be manually edited (as noted in the existing comment).

For your setup:

  • Use npx msw init <PUBLIC_DIR> to copy the worker from the msw package when updating to a new MSW version, then commit the result.
  • MSW runs an integrity check and may surface an "outdated Service Worker" message if the worker drifts from the installed msw version, so keep them in sync.
  • Ensure your bundling config copies this committed worker as needed rather than pulling from elsewhere.
🤖 Prompt for AI Agents
apps/standalone/public/mockServiceWorker.js lines 1-349: The committed
mockServiceWorker.js is currently treated as a generated artifact but the review
requests aligning with MSW best practices; update your workflow so this file is
produced by running `npx msw init <PUBLIC_DIR>` from the project (or copy the
worker from the msw package) whenever MSW is upgraded, commit the resulting file
to source control, and ensure your bundler/static asset pipeline serves the
committed file from apps/standalone/public (do not modify its contents
manually).

Loading