feat: expose the page's query parameters to full-code apps as ctx.query (#12179)

This commit is contained in:
AlexRV12
2026-11-03 17:10:46 +01:00
committed by GitHub
parent c8930fcb07
commit ab15324008
14 changed files with 75 additions and 26 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -230,7 +230,7 @@ const createHTML = (jsPath: string, cssPath: string, appCtx: unknown) => `
</div>
</div>
</div>
<script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")};</script>
<script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")}; window.ctx.query = Object.fromEntries(new URLSearchParams(location.search));</script>
<script src="${jsPath}"></script>
<script>
// Live reload via EventSource
+2
View File
@@ -6782,6 +6782,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
**Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes.
**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads.
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
@@ -34,7 +34,7 @@
path,
onEdit,
onLoadState,
syncHashToUrl = true,
ownsPageUrl = true,
ownsPageHeader = false
}: {
workspace: string
@@ -50,8 +50,8 @@
/** How the load ended, for a host that renders its own state around this viewer.
* A 403 is deliberately neither: the app exists, this member just cannot open it. */
onLoadState?: (state: 'loaded' | 'not_found') => void
/** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */
syncHashToUrl?: boolean
/** Whether a raw app owns the page's address and title; see `RawAppPreview`. */
ownsPageUrl?: boolean
} = $props()
// The app, its permission check and everything this viewer renders belong to `workspace`,
@@ -291,7 +291,7 @@
jwtError={false}
inWorkspace
{hideRefreshBar}
{syncHashToUrl}
{ownsPageUrl}
onLoginSuccess={() => loadApp()}
></PublicApp>
{/snippet}
@@ -23,7 +23,7 @@
license = undefined,
inWorkspace = false,
hideRefreshBar = false,
syncHashToUrl = true
ownsPageUrl = true
}: {
notExists: boolean
noPermission: boolean
@@ -48,8 +48,8 @@
*/
inWorkspace?: boolean
hideRefreshBar?: boolean
/** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */
syncHashToUrl?: boolean
/** Whether a raw app owns the page's address and title; see `RawAppPreview`. */
ownsPageUrl?: boolean
} = $props()
// Use workspace from props or from app.workspace_id (for custom path responses)
@@ -114,7 +114,7 @@
secret={app.bundle_secret}
path={app.path}
runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>}
{syncHashToUrl}
{ownsPageUrl}
/>
</div>
{:else if app.raw_app && !effectiveWorkspace}
@@ -32,6 +32,7 @@
RAW_APP_SANDBOX_FLAGS,
RAW_APP_PREVIEW_RELAY,
rawAppStorageKey,
rawAppCtx,
readRawAppStorage,
applyRawAppStorageOp
} from './utils'
@@ -43,7 +44,7 @@
import type { Modules } from './RawAppModules.svelte'
import { isRunnableByName, isRunnableByPath, type PathRunType } from '../apps/inputType'
import { aiChatManager, AIMode } from '../copilot/chat/AIChatManager.svelte'
import { onMount, onDestroy, untrack } from 'svelte'
import { getContext, onMount, onDestroy, untrack } from 'svelte'
import type {
AppDatatableMetadata,
LintResult,
@@ -1921,9 +1922,17 @@ addEventListener('message', function (e) {
storage: previewStorage()
})
}
// In a session pane the page's query is the session's (`?session=…`), not the app's.
const inSessionPane = !!getContext('aiChatManager')
// The deployed app's `window.ctx`: the viewer's membership in the app's workspace.
function previewCtx() {
function previewCtx() {
return rawAppCtx(
$state.snapshot(operatingUser.current),
opWorkspace,
path,
inSessionPane ? '' : window.location.search
)
}
@@ -7,6 +7,7 @@
RAW_APP_SANDBOX_FLAGS,
applyRawAppStorageOp,
rawAppStorageKey,
rawAppCtx,
readRawAppStorage,
unsandboxedRawAppHtml
} from './utils'
@@ -27,15 +28,17 @@
* (publish flow) needs it to read the app's DOM, which is only possible on
* the unsandboxed path. */
oniframe?: (iframe: HTMLIFrameElement | undefined) => void
/** Mirror the app's own route into the page URL's hash, and start from it, and its
* `document.title` into the page's. Off where the app is embedded in a page that is
* not its own — an AI session preview tab — since there the hash and title belong to
* that page and to whichever app was opened first. */
syncHashToUrl?: boolean
/** Mirror the app's own route into the page URL's hash, and start from it, its
* `document.title` into the page's, and hand it the page's query. Off where the app is
* embedded in a page that is not its own (an AI session preview tab, the demo
* recorder), since there the address and title belong to that page. */
ownsPageUrl?: boolean
}
let { workspace, user, secret, path, runnables, oniframe, syncHashToUrl = true }: Props = $props()
const pageHash = () => (syncHashToUrl ? window.location.hash : '')
let { workspace, user, secret, path, runnables, oniframe, ownsPageUrl = true }: Props = $props()
const pageHash = () => (ownsPageUrl ? window.location.hash : '')
const appCtx = (u: UserExt | undefined) =>
rawAppCtx(u, workspace, path, ownsPageUrl ? window.location.search : '')
$effect(() => {
const el = unsandboxed ? iframe : undefined
@@ -134,7 +137,7 @@
const html = unsandboxedRawAppHtml(
workspace,
secret,
{ ctx: u, workspace, path },
appCtx(u),
window.location.origin,
pageHash()
)
@@ -207,7 +210,7 @@
// Same shape as the unsandboxed wrapper: always the object, so
// `window.ctx.workspace` works for anonymous viewers too. Snapshotted: a
// caller's `$state` user is a proxy, which postMessage cannot clone.
ctx: { ctx: $state.snapshot(user), workspace, path },
ctx: appCtx($state.snapshot(user)),
initialHash,
storage: { local: bundleStorage ?? {}, session: {} },
// The wrapper turns this into `window.process.env` before it injects the
@@ -298,11 +301,11 @@
} else if (data?.type === 'windmill:hashchange') {
// Keep the parent URL hash in sync for shareable URLs.
const newHash = data.hash || ''
if (syncHashToUrl && window.location.hash !== newHash) {
history.replaceState(null, '', newHash || window.location.pathname)
if (ownsPageUrl && window.location.hash !== newHash) {
history.replaceState(null, '', newHash || window.location.pathname + window.location.search)
}
} else if (data?.type === 'windmill:title') {
if (syncHashToUrl) setAppTitle(typeof data.title === 'string' ? data.title : '')
if (ownsPageUrl) setAppTitle(typeof data.title === 'string' ? data.title : '')
} else if (runnerFailed) {
refuseRequest(event)
} else if (!runner) {
@@ -7,6 +7,7 @@ import {
formatRuntimeLogsForChat,
genWmillTs,
normalizeRawAppRuntimeLogs,
rawAppCtx,
rawAppPreviewModules,
stripRawAppDiffNoise,
type Runnable
@@ -53,6 +54,16 @@ const flowSchema = {
}
} as const
describe('rawAppCtx', () => {
it("carries the page's query without Windmill's own parameters", () => {
expect(rawAppCtx(undefined, 'ws', 'u/me/app', '?customer=42&wm_coep=1&tab=b').query).toEqual({
customer: '42',
tab: 'b'
})
expect(rawAppCtx(undefined, 'ws', 'u/me/app', '').query).toEqual({})
})
})
describe('genWmillTs', () => {
it('generates the correct flow args type for path runnables', () => {
const runnables: Record<string, Runnable> = {
@@ -5,6 +5,7 @@ import { isRunnableByName, isRunnableByPath, type RunnableWithFields } from '../
import type { InlineScript } from '../apps/sharedTypes'
import { stateSnapshot } from '$lib/stateSnapshot.svelte'
import { appSourceToDraftValue, normalizeRawAppData } from './rawAppDraftValue'
import { urlParamsToObject } from '$lib/utils/queryParams'
// export type RunnableWithFields = any
@@ -319,6 +320,22 @@ export function applyRawAppStorageOp(storeKey: string, d: any) {
} catch (_) {}
}
/** A full-code app's `window.ctx`, on every path that runs one. `query` is the viewer
* page's, built as a low-code app's `ctx.query`, and `{}` rather than absent. */
export function rawAppCtx(
user: unknown,
workspace: string | undefined,
path: string,
search: string
) {
return {
ctx: user,
workspace,
path,
query: urlParamsToObject(new URLSearchParams(search), { stripReserved: true })
}
}
// The sandboxed (isolated) raw-app wrapper is generated server-side and served as
// a sandboxed, opaque-origin document (see `get_raw_app_data` in the backend
// `apps.rs`, WIN-2006) — a blob: URL cannot carry the `CSP: sandbox` response
@@ -320,7 +320,7 @@
{path}
onEdit={() => onNavigate(`/apps_raw/edit/${path}`)}
onLoadState={setLoadState}
syncHashToUrl={false}
ownsPageUrl={false}
/>
{/if}
{/key}
@@ -202,6 +202,7 @@
{path}
runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>}
oniframe={onIframe}
ownsPageUrl={false}
/>
</div>
{/if}
+2
View File
@@ -1107,6 +1107,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
**Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes.
**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads.
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
@@ -313,6 +313,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.
**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
### Generated bindings (`wmill.d.ts` / `wmill.ts`)
+2
View File
@@ -72,6 +72,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.
**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
### Generated bindings (`wmill.d.ts` / `wmill.ts`)