:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(canvas): make the ph bridge importable as @posthog/canvas-sdk (#87243)
Peter Kirkhamf611bb786c42
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.pyindex ab9b90579fdf..c35bad73b775 100644--- a/products/canvas/backend/tests/test_cloud_builder.py+++ b/products/canvas/backend/tests/test_cloud_builder.py@@ -12,7 +12,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom products.canvas.backend.build_service import node_executable, run_cloud_builder, validate_builder_output-from products.canvas.backend.contract import allowed_import_specifiers, platform_dependencies+from products.canvas.backend.contract import allowed_import_specifiers, canvas_sdk_version, platform_dependenciesfrom products.canvas.backend.presentation.serializers import CanvasSourceProjectSerializerfrom products.canvas.backend.source import synthetic_source_project, validate_source_project@@ -78,7 +78,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):},"entryHtml": "index.html","dependencies": {},- "canvasSdkVersion": "0.1.0",+ "canvasSdkVersion": canvas_sdk_version(),}def _notebook_project(self, source: str, frame_names: list[str] | None = None) -> dict[str, Any]:@@ -204,6 +204,40 @@ class TestCanvasCloudBuilder(SimpleTestCase):self.assertEqual(result["status"], "ready", result["diagnostics"])validate_builder_output(result)+ def test_bundles_the_canvas_sdk_import_inline(self) -> None:+ payload = synthetic_source_project(+ 'import React from "react"; import { ph } from "@posthog/canvas-sdk"; '+ "export default function Canvas() { return <div>{typeof ph}</div> }"+ )++ result = run_cloud_builder(payload)++ self.assertEqual(result["status"], "ready", result["diagnostics"])+ validate_builder_output(result)+ javascript = "\n".join(file["content"] for file in result["files"] if file["path"].endswith(".js"))+ self.assertIn("globalThis.ph", javascript)++ @parameterized.expand(+ [+ ("persisted_before_the_bump", "0.1.0", "ready", []),+ ("never_issued", "0.0.1", "failed", ["unsupported_sdk"]),+ ]+ )+ def test_sdk_version_admission(+ self, _name: str, version: str, expected_status: str, expected_codes: list[str]+ ) -> None:+ # Stored sources keep the canvasSdkVersion they were scaffolded with, so+ # every version the platform ever issued must keep building.+ payload = {+ **synthetic_source_project('import React from "react"; export default () => <div/>'),+ "canvasSdkVersion": version,+ }++ result = run_cloud_builder(payload)++ self.assertEqual(result["status"], expected_status, result["diagnostics"])+ self.assertEqual([entry["code"] for entry in result["diagnostics"]], expected_codes)+def test_runtime_uses_the_document_bound_message_port(self) -> None:result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.pyindex 0624e1561878..e83643116f2d 100644--- a/products/canvas/backend/tests/test_source.py+++ b/products/canvas/backend/tests/test_source.py@@ -51,6 +51,14 @@ class TestCanvasSourceAdapter(SimpleTestCase):def test_valid_minimal_project_has_no_diagnostics(self):self.assertEqual(validate_source_project(project()), [])+ def test_canvas_sdk_import_is_allowed_without_a_dependency_pin(self):+ # The SDK is platform-provided (inlined by the builder), so the import+ # must pass without an entry in the project's dependencies map.+ candidate = project(+ files={CANVAS_COMPONENT_PATH: 'import { ph } from "@posthog/canvas-sdk";\n' + CODE},+ )+ self.assertEqual(validate_source_project(candidate), [])+@parameterized.expand([("wrong_schema_version", project(schemaVersion=2), "unsupported_schema_version"),diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjsindex ff9784581558..e8be84318659 100644--- a/products/canvas/packages/canvas_builder/build.mjs+++ b/products/canvas/packages/canvas_builder/build.mjs@@ -16,6 +16,10 @@ const admitted = Object.fromEntries()const runtimeImports = contract.runtimeImportsconst csp = contract.csp+// Platform-provided, so it is inlined here rather than admitted as a pinned+// dependency; the preview sandbox serves the same source from a blob.+const canvasSdkSpecifier = '@posthog/canvas-sdk'+const canvasSdkModule = readFileSync(new URL('./canvas-sdk.mjs', import.meta.url), 'utf8')const builderDirectory = path.dirname(fileURLToPath(import.meta.url))const builderRequire = createRequire(import.meta.url)const htmlTag = /<(script|link)\b[^>]*>/gi@@ -344,7 +348,9 @@ async function buildPlatformStyles(project) {function validate(project) {const diagnostics = []- if (project.canvasSdkVersion !== '0.1.0') {+ // Sources persist the SDK version they were authored against, so every+ // version ever scaffolded must keep building, so the list only grows.+ if (!contract.supportedSdkVersions.includes(project.canvasSdkVersion)) {diagnostics.push(diagnostic('unsupported_sdk', 'Canvas SDK version is unavailable'))}for (const [name, version] of Object.entries(project.dependencies ?? {})) {@@ -382,6 +388,9 @@ async function bundleEntry(project, entry) {if (!['canvas', 'canvas-worker'].includes(args.namespace)) {return undefined}+ if (args.path === canvasSdkSpecifier) {+ return { path: canvasSdkSpecifier, namespace: 'canvas-sdk' }+ }if (args.path.startsWith('.') || args.path.startsWith('/')) {const workerImport = args.path.endsWith('?worker')const requestedPath = workerImport ? args.path.slice(0, -7) : args.path@@ -408,6 +417,10 @@ async function bundleEntry(project, entry) {pluginData: { platformDependency: true },})})+ pluginBuild.onLoad({ filter: /.*/, namespace: 'canvas-sdk' }, () => ({+ contents: canvasSdkModule,+ loader: 'js',+ }))pluginBuild.onLoad({ filter: /.*/, namespace: 'canvas' }, (args) => ({contents: files[args.path],loader: loader(args.path),diff --git a/products/canvas/packages/canvas_builder/canvas-sdk.mjs b/products/canvas/packages/canvas_builder/canvas-sdk.mjsnew file mode 100644index 000000000000..1157f27e00bb--- /dev/null+++ b/products/canvas/packages/canvas_builder/canvas-sdk.mjs@@ -0,0 +1,9 @@+// The `@posthog/canvas-sdk` module a canvas imports: a facade over the `ph`+// bridge the runtime installs on the window before any canvas code runs, so+// canvases reaching for the `window.ph` global keep working.+//+// The desktop vendors this source into CANVAS_SDK_MODULE_SOURCE+// (products/desktop/packages/shared/src/canvas-platform.ts) to serve the same+// module in the edit preview. Change one, change the other.+export const ph = globalThis.ph+export default globalThis.phdiff --git a/products/canvas/packages/canvas_builder/manifest.json b/products/canvas/packages/canvas_builder/manifest.jsonindex 7f3bedfd593b..ed0064b747a9 100644--- a/products/canvas/packages/canvas_builder/manifest.json+++ b/products/canvas/packages/canvas_builder/manifest.json@@ -1,6 +1,7 @@{"$comment": "Single source of truth for the canvas platform contract. Loaded by build.mjs (bundling), the Python validator/build service (products/canvas/backend/source.py), and the artifact origin's CSP (products/canvas/backend/presentation/artifacts.py). The desktop app's freeform whitelist is asserted against this file by a contract test.",- "canvasSdkVersion": "0.1.0",+ "canvasSdkVersion": "0.2.0",+ "supportedSdkVersions": ["0.1.0", "0.2.0"],"dependencies": {"react": { "version": "19.0.0", "url": "https://esm.sh/[email protected]" },"react-dom": { "version": "19.0.0", "url": "https://esm.sh/[email protected]?external=react" },@@ -36,6 +37,7 @@"react-dom/client": "https://esm.sh/[email protected]/client?external=react"},"allowedImportSpecifiers": [+ "@posthog/canvas-sdk","react","react-dom","react-dom/client",diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.mdindex 77344b66a49d..b36c115eafba 100644--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md@@ -25,6 +25,10 @@ Use React, Quill, Recharts, Lucide, and Day.js for the standard application shelalso admits ten optional libraries for specialized work. Read[references/platform-libraries.md](references/platform-libraries.md) before choosing one.+PostHog data comes through `import { ph } from "@posthog/canvas-sdk"` — a platform-provided+module, so it needs no `dependencies` entry. The same object exists as the `window.ph` global+(how existing canvases reach it); prefer the import in new code.+Other bare imports, dynamic `import()`, `require()`, `<script>` tags, and remote code failvalidation. Direct network requests and external images, fonts, media, or frames require an exactHTTPS origin in `capabilities.network.origins`. They work only in the **published** canvas — thediff --git a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.mdindex 3716dd60a79a..88da3f813415 100644--- a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md+++ b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md@@ -263,5 +263,6 @@ export default function Canvas() {}```-Note: `ph` is a global the host injects into the sandbox (`window.ph`) — do not import it, and do-not import or initialize posthog-js.+Note: reach PostHog through `import { ph } from "@posthog/canvas-sdk"`, a platform-provided module+that needs no `dependencies` entry. The host also injects the same object as the `window.ph`+global. Never initialize it, and do not import or initialize posthog-js.diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.mdindex 3fc71c97c149..814ce0310c4b 100644--- a/products/canvas/skills/querying-canvas-data/SKILL.md+++ b/products/canvas/skills/querying-canvas-data/SKILL.md@@ -11,12 +11,16 @@ description: ># Querying canvas data-The global `ph` object (injected by the host — never imported, never initialized) is the only way-a canvas talks to PostHog. Credentials stay in the host; `fetch()`, posthog-js, and hand-rolled-clients cannot reach PostHog from the sandbox. External requests and resources require a non-PostHog-origin declared in `capabilities.network.origins`, and work only in the published canvas — the-edit-mode preview blocks all direct network access. This includes external stylesheets; remote-scripts remain blocked.+The `ph` bridge is the only way a canvas talks to PostHog. Import it with+`import { ph } from "@posthog/canvas-sdk"` — a platform-provided module, so it needs no+`dependencies` entry. The same object is also installed as the `window.ph` global, which existing+canvases use; prefer the import in new code. Its typed surface is+[references/canvas-sdk.d.ts](references/canvas-sdk.d.ts). Never initialize it: credentials stay in+the host, and `fetch()`, posthog-js, and hand-rolled clients cannot reach PostHog from the sandbox.+External requests and resources require a non-PostHog origin declared in+`capabilities.network.origins`, and work only in the published canvas — the edit-mode preview+blocks all direct network access. This includes external stylesheets; remote scripts remain+blocked.## Data hierarchy — back every metric with a saved insightdiff --git a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.tsnew file mode 100644index 000000000000..b917a20a9617--- /dev/null+++ b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts@@ -0,0 +1,160 @@+// Typed surface of `@posthog/canvas-sdk`, the `ph` bridge, for canvas authors+// and authoring agents. Reference only: nothing type-checks against it, and the+// methods are served by the host over postMessage, so this describes the+// protocol rather than implementing it. The implementation is+// products/canvas/packages/canvas_builder/canvas-sdk.mjs.+//+// A published canvas is held to `project.capabilities` at runtime: every insight+// short id, capture event name, state scope, and action verb must be declared,+// and ad-hoc `ph.query` needs `inlineQueries: true`.++/**+ * One trends-style series. `ph.loadInsight` and a typed query node return these+ * as `results` (see CanvasDataResult), so cast when you know the query kind.+ */+export interface CanvasSeriesResult {+ /** Per-interval values, aligned with `days`. */+ data: number[]+ /** ISO dates for each interval. */+ days: string[]+ /** Human labels for each interval. */+ labels: string[]+ /** Sum across the window, which is the usual KPI total. */+ count?: number+ /** Single-value total for aggregated displays. */+ aggregated_value?: number+ /** Series label. */+ label?: string+ /** Set when the query has a compare period; match on this, never on index. */+ compare_label?: 'current' | 'previous'+}++/**+ * Result of `ph.loadInsight` and `ph.query`. The element shape depends on the+ * query kind, which is why `results` is not narrowed here:+ * - Trends-style (typed insight nodes): series objects, so cast to+ * `CanvasSeriesResult[]`. `columns` is empty.+ * - SQL: rows, each an array of cell values in `columns` order.+ * Funnels, retention, and paths return their own PostHog-native shapes.+ */+export interface CanvasDataResult {+ columns: string[]+ results: unknown[]+}++export interface CanvasDateRange {+ date_from?: string | null+ date_to?: string | null+}++export interface CanvasLoadInsightOptions {+ /** Re-scope the saved insight to this window (a saved SQL insight may ignore it). */+ dateRange?: CanvasDateRange+ /**+ * Values for a SQL insight's `{variables.name}` placeholders, keyed by code+ * name. The host rejects a variable the insight doesn't use.+ */+ variables?: Record<string, unknown>+ /** Cache lifetime in whole seconds, 30–86400. */+ refresh?: number+}++export interface CanvasQueryOptions {+ /** Cache lifetime in whole seconds, 30–86400. */+ refresh?: number+}++/** "user" (default) is private to the viewer; "shared" is one value per canvas, team-visible. */+export type CanvasStateScope = 'user' | 'shared'++export interface CanvasStateEntry {+ scope: CanvasStateScope+ key: string+ value: unknown+ updatedAt?: string+}++export interface CanvasState {+ /** Resolves to the stored JSON value, or null when unset. */+ get(key: string, options?: { scope?: CanvasStateScope }): Promise<unknown>+ /**+ * Stores a JSON value (64 KB serialized cap, 256 keys per scope). Setting+ * null deletes the key.+ */+ set(key: string, value: unknown, options?: { scope?: CanvasStateScope }): Promise<{ ok: boolean }>+ list(options?: { scope?: CanvasStateScope }): Promise<CanvasStateEntry[]>+}++export interface CanvasActions {+ /**+ * Write into PostHog as the viewer; the result shape depends on the verb.+ * Every verb must be declared in `capabilities.posthog.actions`, and calls+ * belong on an explicit user gesture (a button), never on load or render.+ */+ invoke(verb: string, payload?: Record<string, unknown>): Promise<unknown>+}++export interface CanvasAgentRequestResult {+ requestOutcome: 'signaled' | 'new_run' | 'already_queued' | 'reported'+ taskId: string+}++export interface CanvasAgent {+ /**+ * Ask the canvas's authoring agent for a change. The host shows the exact+ * prompt and asks the viewer to approve before anything is dispatched.+ * Requires `capabilities.posthog.agentRequests`.+ */+ request(prompt: string): Promise<CanvasAgentRequestResult>+}++/** In-app navigation. Only these four targets exist. */+export interface CanvasNavigate {+ toTask(taskId: string): void+ toNewTask(): void+ toCanvas(canvasId: string): void+ toNewCanvas(): void+}++export interface CanvasSdk {+ /**+ * PREFERRED data path: load a saved insight by short id and render its stored+ * result. Declare the short id in `capabilities.posthog.insights`.+ */+ loadInsight(shortId: string, options?: CanvasLoadInsightOptions): Promise<CanvasDataResult>+ /**+ * Run a typed query node (`{ kind: "TrendsQuery", … }`, preferred, because numbers+ * match the PostHog UI) or an inline HogQL string (escape hatch). Requires+ * `capabilities.posthog.inlineQueries` in a published canvas.+ */+ query(+ query: Record<string, unknown> | string,+ params?: Record<string, unknown>,+ options?: CanvasQueryOptions+ ): Promise<CanvasDataResult>+ /**+ * Send an analytics event (properties capped at 16 KB serialized). Declare+ * each event name in `capabilities.posthog.captureEvents`.+ */+ capture(event: string, properties?: Record<string, unknown>, distinctId?: string): Promise<{ ok: boolean }>+ /** Open a PostHog URL externally. https://posthog.com / *.posthog.com only. */+ openExternal(url: string): void+ state: CanvasState+ actions: CanvasActions+ agent: CanvasAgent+ /**+ * Frozen per-placement config parsed at boot. Published/component runtime+ * only; undefined in the edit-mode preview.+ */+ config?: Readonly<Record<string, unknown>>+ /** Preview runtime only today; undefined in a published canvas. */+ navigate?: CanvasNavigate+}++/**+ * The canvas's PostHog bridge, the same object as the `window.ph` global. Both+ * are installed on the document, so a `?worker` bundle cannot reach them.+ */+export declare const ph: CanvasSdk+declare const defaultPh: CanvasSdk+export default defaultPhdiff --git a/products/desktop/packages/core/src/canvas/freeformWhitelist.contract.test.ts b/products/desktop/packages/core/src/canvas/freeformWhitelist.contract.test.tsindex 12128b93f86a..c60051b00f00 100644--- a/products/desktop/packages/core/src/canvas/freeformWhitelist.contract.test.ts+++ b/products/desktop/packages/core/src/canvas/freeformWhitelist.contract.test.ts@@ -1,12 +1,37 @@-import { CANVAS_PLATFORM_MANIFEST } from "@posthog/shared";+import {+ CANVAS_PLATFORM_MANIFEST,+ CANVAS_SDK_MODULE_SOURCE,+ CANVAS_SDK_SPECIFIER,+} from "@posthog/shared";import { describe, expect, it } from "vitest";-import { FREEFORM_WHITELIST } from "./freeformWhitelist";+import { buildImportMap, FREEFORM_WHITELIST } from "./freeformWhitelist";function isSubpathSpecifier(name: string): boolean {const segments = name.split("/");return name.startsWith("@") ? segments.length > 2 : segments.length > 1;}+// Comments and blank lines carry no module semantics, and the vendored copy+// drops the original's header, so compare only the code.+function codeLines(source: string): string[] {+ return source+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line !== "" && !line.startsWith("//"));+}++function builderFile(relativePath: string): Promise<string> {+ return import("node:fs/promises").then(({ readFile }) =>+ readFile(+ new URL(+ `../../../../../canvas/packages/canvas_builder/${relativePath}`,+ import.meta.url,+ ).pathname,+ "utf8",+ ),+ );+}+describe("freeform whitelist ↔ platform dependency registry", () => {// The legacy runtime's import whitelist and the build pipeline's platform// dependency registry describe the same pinned package set. If one moves@@ -25,6 +50,55 @@ describe("freeform whitelist ↔ platform dependency registry", () => {expect(whitelist).toEqual(registry);});+ // CANVAS_PLATFORM_MANIFEST is a hand-vendored copy of the builder's+ // manifest.json, so it can silently fall behind. Drift in the fields below+ // ships, because the client reads them: admit an import specifier or bump the+ // SDK version server-side without copying it here, and a canvas previews+ // against one contract but publishes against another. `csp` and `limits` are+ // vendored but unread, and are deliberately left out of this comparison.+ it("matches the builder's manifest on the fields the client reads", async () => {+ const manifest = JSON.parse(await builderFile("manifest.json"));++ expect(CANVAS_PLATFORM_MANIFEST.canvasSdkVersion).toEqual(+ manifest.canvasSdkVersion,+ );+ expect(CANVAS_PLATFORM_MANIFEST.supportedSdkVersions).toEqual(+ manifest.supportedSdkVersions,+ );+ expect(CANVAS_PLATFORM_MANIFEST.allowedImportSpecifiers).toEqual(+ manifest.allowedImportSpecifiers,+ );+ expect(CANVAS_PLATFORM_MANIFEST.dependencies).toEqual(+ manifest.dependencies,+ );+ expect(CANVAS_PLATFORM_MANIFEST.runtimeImports).toEqual(+ manifest.runtimeImports,+ );+ });++ // Admission and resolution used to be one list. Now the preview admits what+ // the manifest admits but still resolves through FREEFORM_WHITELIST, so a+ // specifier added server-side passes the import check and then dies in the+ // iframe on "Failed to resolve module specifier". The SDK is the one+ // exception: the document mints it as a blob at load time.+ it("resolves every admitted import specifier in the preview import map", () => {+ const { imports } = buildImportMap();++ for (const specifier of CANVAS_PLATFORM_MANIFEST.allowedImportSpecifiers) {+ if (specifier === CANVAS_SDK_SPECIFIER) continue;+ expect(imports[specifier], specifier).toBeTruthy();+ }+ });++ // The preview serves its own copy of the SDK module, so a change to the+ // builder's copy alone ships an author an export that resolves in one tier+ // and is undefined in the other.+ it("vendors the builder's canvas SDK module verbatim", async () => {+ expect(codeLines(CANVAS_SDK_MODULE_SOURCE)).toEqual(+ codeLines(await builderFile("canvas-sdk.mjs")),+ );+ });+it("covers every whitelisted subpath specifier with a runtime import", () => {for (const entry of FREEFORM_WHITELIST.filter((e) =>isSubpathSpecifier(e.name),diff --git a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts b/products/desktop/packages/core/src/canvas/freeformWhitelist.tsindex 97d3ef17391d..50c090973228 100644--- a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts+++ b/products/desktop/packages/core/src/canvas/freeformWhitelist.ts@@ -1,3 +1,5 @@+import { CANVAS_PLATFORM_MANIFEST } from "@posthog/shared";+// The package whitelist for freeform-React canvases (Q16: curated, PostHog-// anchored). Every entry is a package the agent may import; anything else is// rejected by the static check below. Keep this list SMALL — each entry is@@ -121,11 +123,14 @@ export const FREEFORM_BABEL_URL = `${ESM}/@babel/[email protected]`;// self-host it in the bundle. Pinned so a canvas can't drift onto a new major.export const FREEFORM_POSTHOG_JS_URL = `${ESM}/[email protected]`;-// Names the agent is allowed to import. Subpath imports (e.g. "dayjs/plugin/x")-// are allowed when their package root is whitelisted AND the exact subpath is-// listed; we keep it strict (exact-match only) so a subpath can't smuggle in an-// unreviewed entry point.-const ALLOWED_SPECIFIERS = new Set(FREEFORM_WHITELIST.map((e) => e.name));+// Names the agent is allowed to import, taken from the platform contract so the+// preview admits exactly what the builder does. It is a superset of+// FREEFORM_WHITELIST: platform-provided modules like the canvas SDK are+// importable without a CDN pin. Subpath imports (e.g. "dayjs/plugin/x") must be+// listed exactly, so a subpath can't smuggle in an unreviewed entry point.+const ALLOWED_SPECIFIERS = new Set<string>(+ CANVAS_PLATFORM_MANIFEST.allowedImportSpecifiers,+);// The import map handed to the iframe so bare specifiers resolve to the pinned// modules. Edit mode -> esm.sh; view mode (Phase 2) will pass self-hosted URLs.diff --git a/products/desktop/packages/shared/src/canvas-platform.ts b/products/desktop/packages/shared/src/canvas-platform.tsindex 314ee441dd16..59d3e34eccb6 100644--- a/products/desktop/packages/shared/src/canvas-platform.ts+++ b/products/desktop/packages/shared/src/canvas-platform.ts@@ -4,7 +4,8 @@// legacy import map (freeformWhitelist) is contract-tested against the same// pins. When the server manifest changes, update this constant to match.export const CANVAS_PLATFORM_MANIFEST = {- canvasSdkVersion: "0.1.0",+ canvasSdkVersion: "0.2.0",+ supportedSdkVersions: ["0.1.0", "0.2.0"],dependencies: {react: {version: "19.0.0",@@ -67,6 +68,7 @@ export const CANVAS_PLATFORM_MANIFEST = {"react-dom/client": "https://esm.sh/[email protected]/client?external=react",},allowedImportSpecifiers: [+ "@posthog/canvas-sdk","react","react-dom","react-dom/client",@@ -95,3 +97,15 @@ export const CANVAS_PLATFORM_MANIFEST = {maxArtifactTotalBytes: 12582912,},} as const;++// The platform-provided canvas SDK. It carries no CDN pin because neither tier+// fetches it: the builder inlines the module and the preview sandbox serves it+// from a blob, so the project-wide canvasSdkVersion governs it.+export const CANVAS_SDK_SPECIFIER = "@posthog/canvas-sdk";++// Vendored from products/canvas/packages/canvas_builder/canvas-sdk.mjs with its+// comments elided. Copied rather than imported because the builder ships inside+// its own build image and cannot reach this workspace.+export const CANVAS_SDK_MODULE_SOURCE = `export const ph = globalThis.ph+export default globalThis.ph+`;diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.tsindex dfb6da449587..1d68ab3c99c4 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts@@ -1,3 +1,7 @@+import {+ CANVAS_SDK_MODULE_SOURCE,+ CANVAS_SDK_SPECIFIER,+} from "@posthog/shared";import { describe, expect, it } from "vitest";import {buildSandboxDocument,@@ -14,6 +18,47 @@ function clickTarget(html: string, selector: string): Element {return element;}+// Runs the document's import-map setup script against stub Blob/URL/document+// globals and returns the map it installs. jsdom has no createObjectURL, and+// asserting the map it produces beats matching the script's source text.+function installedImportMap(html: string): Record<string, string> {+ const setup = [+ ...new DOMParser()+ .parseFromString(html, "text/html")+ .querySelectorAll("script"),+ ].find((script) => script.textContent?.includes("canvasImportMap"));+ if (!setup?.textContent) throw new Error("import-map setup script not found");++ const blobs: string[] = [];+ const installed: { type?: string; textContent?: string } = {};+ const documentStub = {+ createElement: () => installed,+ head: { appendChild: () => undefined },+ };+ const urlStub = {+ createObjectURL: (blob: { parts: string[] }) =>+ `blob:${blobs.push(blob.parts.join("")) - 1}`,+ };+ class BlobStub {+ constructor(public parts: string[]) {}+ }++ new Function("document", "URL", "Blob", setup.textContent)(+ documentStub,+ urlStub,+ BlobStub,+ );++ expect(installed.type).toBe("importmap");+ const imports = JSON.parse(installed.textContent ?? "{}").imports;+ // Resolve blob handles back to their source so callers can assert content.+ for (const [name, url] of Object.entries(imports)) {+ const index = /^blob:(\d+)$/.exec(String(url))?.[1];+ if (index) imports[name] = blobs[Number(index)];+ }+ return imports;+}+describe("decodeJsxUnicodeEscapes", () => {it.each([{@@ -66,6 +111,18 @@ describe("buildSandboxDocument", () => {expect(html).toContain("jsxUnicodeEscapesPlugin");});+ // The SDK has no CDN pin, so it resolves only if the document mints it as a+ // blob module and registers it. Assembling the map at runtime also has to+ // keep the CDN pins it replaced, because losing those breaks every canvas+ // rather than only the ones importing the SDK.+ it("registers the canvas SDK alongside the CDN pins in the import map", () => {+ const imports = installedImportMap(buildSandboxDocument());++ expect(imports[CANVAS_SDK_SPECIFIER]).toBe(CANVAS_SDK_MODULE_SOURCE);+ expect(imports.react).toContain("esm.sh");+ expect(imports["react/jsx-runtime"]).toContain("esm.sh");+ });+it("inlines the external-anchor resolver into the bootstrap", () => {const html = buildSandboxDocument();expect(html).toContain(diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex 93b570c8e044..9f08b848b281 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -6,6 +6,10 @@ import {FREEFORM_QUILL_CSS_URLS,} from "@posthog/core/canvas/freeformWhitelist";import { resolveTextCommentAnchor } from "@posthog/core/comments/anchors";+import {+ CANVAS_SDK_MODULE_SOURCE,+ CANVAS_SDK_SPECIFIER,+} from "@posthog/shared";import {commentActionAnchorRect,installSelectionSettleGate,@@ -670,7 +674,19 @@ export function buildSandboxDocument(<head><meta charset="utf-8" /><meta http-equiv="Content-Security-Policy" content="${csp}" />-<script type="importmap">${importMap}</script>+<script>+ // The map is assembled here rather than baked into the HTML because+ // "@posthog/canvas-sdk" is platform-provided rather than CDN-pinned, and the+ // blob holding it only exists inside this document. Keep this ahead of the+ // bootstrap module: a map added after module loading starts is ignored.+ var canvasImportMap = ${importMap};+ canvasImportMap.imports[${JSON.stringify(CANVAS_SDK_SPECIFIER)}] =+ URL.createObjectURL(new Blob([${JSON.stringify(CANVAS_SDK_MODULE_SOURCE)}], { type: "text/javascript" }));+ var canvasImportMapTag = document.createElement("script");+ canvasImportMapTag.type = "importmap";+ canvasImportMapTag.textContent = JSON.stringify(canvasImportMap);+ document.head.appendChild(canvasImportMapTag);+</script>${tailwind}${reset}${FREEFORM_QUILL_CSS_URLS.map(diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 0a72130b7042..8cb6027063b2 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -500,6 +500,7 @@ def _build_canvas_template_image() -> modal.Image:.run_commands("npm ci --prefix /scripts --omit=dev --no-audit --no-fund").add_local_file(str(builder_dir / "build.mjs"), "/scripts/canvas-builder/build.mjs", copy=True).add_local_file(str(builder_dir / "manifest.json"), "/scripts/canvas-builder/manifest.json", copy=True)+ .add_local_file(str(builder_dir / "canvas-sdk.mjs"), "/scripts/canvas-builder/canvas-sdk.mjs", copy=True))