@nullplatform/ui-plugin-sdk 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+ import "./polyfill.js";
2
+ import type { CanvasInput, CanvasTheme, CanvasTooltip, HostMessage } from "./protocol.js";
3
+ import type { CanvasCursor } from "./catalog.js";
4
+ export type { CanvasInput, CanvasTheme, CanvasTooltip } from "./protocol.js";
5
+ /** What a draw call gets: the size in CSS pixels (the context is already scaled to it) and the host theme. */
6
+ export interface CanvasFrame {
7
+ width: number;
8
+ height: number;
9
+ dpr: number;
10
+ theme: CanvasTheme;
11
+ }
12
+ export interface CanvasOptions {
13
+ /** Draws the whole picture. The context is cleared and scaled to CSS pixels before each call. */
14
+ draw(ctx: OffscreenCanvasRenderingContext2D, frame: CanvasFrame): void;
15
+ /** Pointer, wheel and key input in CSS pixels. Call `invalidate()` on the handle when the picture changes. */
16
+ onInput?(input: CanvasInput, frame: CanvasFrame): void;
17
+ }
18
+ export interface CanvasHandle {
19
+ /** The id to pass to `<Canvas surface>`. */
20
+ readonly surface: string;
21
+ /** The current size and theme, once the host sent them. */
22
+ readonly frame: CanvasFrame | null;
23
+ /** Redraws: right after the input being handled, or on the next task outside one. */
24
+ invalidate(): void;
25
+ /** Asks the host to draw its own tooltip at `x`, `y`, or to clear it with `null`. Anchor it to the item, not the pointer. */
26
+ tooltip(tooltip: CanvasTooltip | null): void;
27
+ }
28
+ /** Whether this worker can draw: OffscreenCanvas with a 2D context (Safari before 16.4 has neither). */
29
+ export declare const canDrawCanvas: boolean;
30
+ /** Called by the worker runtime once it has the host port. */
31
+ export declare function attachCanvasPort(next: MessagePort): void;
32
+ /** Handles the host's canvas messages; the worker runtime routes them here. */
33
+ export declare function receiveCanvas(message: Extract<HostMessage, {
34
+ type: "canvas-size" | "canvas-input";
35
+ }>): void;
36
+ /**
37
+ * A surface to draw on with `<Canvas>`. `draw` runs on every redraw with a cleared context in CSS pixels; `onInput`
38
+ * gets the pointer, wheel and keys. Both may change between renders: the latest ones run.
39
+ */
40
+ export declare function useCanvas(options: CanvasOptions): CanvasHandle;
41
+ export interface CanvasItem {
42
+ id: string;
43
+ label: string;
44
+ description?: string;
45
+ }
46
+ export type CanvasProps = {
47
+ /** The handle from `useCanvas`. */
48
+ canvas: CanvasHandle;
49
+ height?: number;
50
+ /** What the drawing shows, for assistive technology. */
51
+ label: string;
52
+ /** What the drawing contains, as a list for assistive technology, and shown where the worker can't draw. */
53
+ items?: CanvasItem[];
54
+ cursor?: CanvasCursor;
55
+ /** Takes the wheel for zoom instead of scrolling the page. */
56
+ captureWheel?: boolean;
57
+ /** An item activated in that list. */
58
+ onItemPress?: (id: string) => void;
59
+ };
60
+ /**
61
+ * A surface the plugin draws itself. Needs `permissions.canvas` in the manifest; without it, or on a host that
62
+ * predates the element, `hostRenders(Canvas)` is false: draw something else then.
63
+ */
64
+ export declare const Canvas: {
65
+ ({ canvas, ...props }: CanvasProps): import("react").ReactElement<{
66
+ surface: string;
67
+ height?: number;
68
+ label: string;
69
+ items?: CanvasItem[];
70
+ cursor?: CanvasCursor;
71
+ captureWheel?: boolean;
72
+ fallback?: boolean;
73
+ onItemPress?: (id: string) => void;
74
+ } & {
75
+ children?: import("react").ReactNode;
76
+ }, string | import("react").JSXElementConstructor<any>>;
77
+ displayName: string;
78
+ };
package/dist/canvas.js ADDED
@@ -0,0 +1,151 @@
1
+ import "./polyfill.js";
2
+ /**
3
+ * Worker side of np-canvas: the surfaces a plugin draws, each an OffscreenCanvas the host sizes. A plugin draws with
4
+ * Canvas 2D in CSS pixels; each frame leaves as an ImageBitmap, transferred to the host with no copy.
5
+ *
6
+ * Input arrives paced by the host: a pointer move only after the plugin answered the previous one. So the plugin
7
+ * draws right away, inside the input handler, and answers with that frame (or an ack when nothing changed).
8
+ */
9
+ import { createElement, useEffect, useRef, useState } from "react";
10
+ import { component } from "./component.js";
11
+ import { registerTag } from "./host.js";
12
+ /** Whether this worker can draw: OffscreenCanvas with a 2D context (Safari before 16.4 has neither). */
13
+ export const canDrawCanvas = (() => {
14
+ try {
15
+ return typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ })();
21
+ let port = null;
22
+ const surfaces = new Map();
23
+ let counter = 0;
24
+ /** Called by the worker runtime once it has the host port. */
25
+ export function attachCanvasPort(next) {
26
+ port = next;
27
+ }
28
+ function present(surface) {
29
+ const { canvas, ctx, frame } = surface;
30
+ if (!port || !canvas || !ctx || !frame)
31
+ return;
32
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
33
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
34
+ // `transferToImageBitmap` gives the canvas a fresh backing but keeps the context state, transform included.
35
+ ctx.setTransform(frame.dpr, 0, 0, frame.dpr, 0, 0);
36
+ surface.options.current.draw(ctx, frame);
37
+ const bitmap = canvas.transferToImageBitmap();
38
+ port.postMessage({ type: "canvas-frame", surface: surface.id, bitmap, seq: surface.seq }, [bitmap]);
39
+ }
40
+ function invalidate(surface) {
41
+ if (surface.handling) {
42
+ surface.dirty = true;
43
+ return;
44
+ }
45
+ if (surface.scheduled)
46
+ return;
47
+ surface.scheduled = true;
48
+ setTimeout(() => {
49
+ surface.scheduled = false;
50
+ if (surfaces.get(surface.id) === surface)
51
+ present(surface);
52
+ }, 0);
53
+ }
54
+ /** Handles the host's canvas messages; the worker runtime routes them here. */
55
+ export function receiveCanvas(message) {
56
+ const surface = surfaces.get(message.surface);
57
+ if (!surface) {
58
+ // An input for a surface already gone still needs an answer, or the host holds the next one back.
59
+ if (message.type === "canvas-input")
60
+ port?.postMessage({ type: "canvas-ack", surface: message.surface, seq: message.seq });
61
+ return;
62
+ }
63
+ if (message.type === "canvas-size") {
64
+ const { width, height, dpr, theme } = message;
65
+ surface.frame = { width, height, dpr, theme };
66
+ if (!canDrawCanvas)
67
+ return;
68
+ const pixelWidth = Math.max(1, Math.round(width * dpr));
69
+ const pixelHeight = Math.max(1, Math.round(height * dpr));
70
+ if (!surface.canvas) {
71
+ surface.canvas = new OffscreenCanvas(pixelWidth, pixelHeight);
72
+ surface.ctx = surface.canvas.getContext("2d");
73
+ }
74
+ else {
75
+ surface.canvas.width = pixelWidth;
76
+ surface.canvas.height = pixelHeight;
77
+ }
78
+ present(surface);
79
+ return;
80
+ }
81
+ surface.seq = message.seq;
82
+ surface.handling = true;
83
+ surface.dirty = false;
84
+ try {
85
+ if (surface.frame)
86
+ surface.options.current.onInput?.(message.input, surface.frame);
87
+ }
88
+ finally {
89
+ surface.handling = false;
90
+ }
91
+ if (surface.dirty && surface.frame)
92
+ present(surface);
93
+ else
94
+ port?.postMessage({ type: "canvas-ack", surface: surface.id, seq: message.seq });
95
+ surface.dirty = false;
96
+ }
97
+ /**
98
+ * A surface to draw on with `<Canvas>`. `draw` runs on every redraw with a cleared context in CSS pixels; `onInput`
99
+ * gets the pointer, wheel and keys. Both may change between renders: the latest ones run.
100
+ */
101
+ export function useCanvas(options) {
102
+ const latest = useRef(options);
103
+ latest.current = options;
104
+ const [surface] = useState(() => {
105
+ const created = {
106
+ id: `cv-${++counter}`,
107
+ options: latest,
108
+ canvas: null,
109
+ ctx: null,
110
+ frame: null,
111
+ seq: 0,
112
+ dirty: false,
113
+ handling: false,
114
+ scheduled: false,
115
+ lastTooltip: "null",
116
+ };
117
+ // Registered while rendering, not in an effect: the host may answer the element with its size before effects run.
118
+ surfaces.set(created.id, created);
119
+ return created;
120
+ });
121
+ const [handle] = useState(() => ({
122
+ surface: surface.id,
123
+ get frame() {
124
+ return surface.frame;
125
+ },
126
+ invalidate: () => invalidate(surface),
127
+ tooltip(tooltip) {
128
+ const key = JSON.stringify(tooltip);
129
+ // Unchanged tooltips don't cross: a hover sends one per item, not one per pointer move.
130
+ if (key === surface.lastTooltip)
131
+ return;
132
+ surface.lastTooltip = key;
133
+ port?.postMessage({ type: "canvas-overlay", surface: surface.id, tooltip });
134
+ },
135
+ }));
136
+ useEffect(() => {
137
+ surfaces.set(surface.id, surface);
138
+ return () => {
139
+ surfaces.delete(surface.id);
140
+ };
141
+ }, [surface]);
142
+ return handle;
143
+ }
144
+ const RemoteCanvas = component("np-canvas");
145
+ /**
146
+ * A surface the plugin draws itself. Needs `permissions.canvas` in the manifest; without it, or on a host that
147
+ * predates the element, `hostRenders(Canvas)` is false: draw something else then.
148
+ */
149
+ export const Canvas = ({ canvas, ...props }) => createElement(RemoteCanvas, { ...props, surface: canvas.surface, ...(canDrawCanvas ? {} : { fallback: true }) });
150
+ Canvas.displayName = "Canvas";
151
+ registerTag(Canvas, "np-canvas");
package/dist/catalog.d.ts CHANGED
@@ -83,6 +83,15 @@ export declare const CATALOG_PROP_VALUES: {
83
83
  readonly Scatter: {
84
84
  readonly xScale: readonly ["linear", "log"];
85
85
  };
86
+ readonly Canvas: {
87
+ readonly cursor: readonly ["default", "pointer", "grab", "grabbing", "crosshair", "move"];
88
+ };
89
+ };
90
+ /** Caps the host holds a canvas element's props to: the catalog only types them. */
91
+ export declare const CANVAS_LIMITS: {
92
+ readonly height: 1600;
93
+ readonly items: 2000;
94
+ readonly label: 200;
86
95
  };
87
96
  /**
88
97
  * Every element a plugin can render: the SDK's own, then the design-system components whose contracts
@@ -105,5 +114,6 @@ export type AlertSeverity = (typeof CATALOG_PROP_VALUES.Alert.severity)[number];
105
114
  export type LinkColor = (typeof CATALOG_PROP_VALUES.Link.color)[number];
106
115
  export type LinkUnderline = (typeof CATALOG_PROP_VALUES.Link.underline)[number];
107
116
  export type ScatterScale = (typeof CATALOG_PROP_VALUES.Scatter.xScale)[number];
117
+ export type CanvasCursor = (typeof CATALOG_PROP_VALUES.Canvas.cursor)[number];
108
118
  /** Name of the wrapper element remote-dom uses for React elements passed as props. */
109
119
  export declare const FRAGMENT_TAG = "remote-fragment";
package/dist/catalog.js CHANGED
@@ -56,7 +56,12 @@ export const CATALOG_PROP_VALUES = {
56
56
  Scatter: {
57
57
  xScale: ["linear", "log"],
58
58
  },
59
+ Canvas: {
60
+ cursor: ["default", "pointer", "grab", "grabbing", "crosshair", "move"],
61
+ },
59
62
  };
63
+ /** Caps the host holds a canvas element's props to: the catalog only types them. */
64
+ export const CANVAS_LIMITS = { height: 1600, items: 2000, label: 200 };
60
65
  /** The elements the SDK defines itself. */
61
66
  const OWN_CATALOG = [
62
67
  {
@@ -402,6 +407,26 @@ const OWN_CATALOG = [
402
407
  values: CATALOG_PROP_VALUES.Scatter,
403
408
  cssValues: ["points[].color"],
404
409
  },
410
+ {
411
+ // A surface the plugin draws itself, with Canvas 2D in its worker, sent to the host as frames. Needs the
412
+ // `permissions.canvas` manifest permission, which the install flow should show: the plugin can paint anything inside
413
+ // its rectangle. `items` lists what it draws for assistive technology (and as the fallback where the worker can't
414
+ // draw); `itemPress` sends the id of the one activated there. Not every host draws it: see `hostRenders`.
415
+ tag: "np-canvas",
416
+ component: "Canvas",
417
+ properties: {
418
+ surface: "string",
419
+ height: "number",
420
+ label: "string",
421
+ items: "array",
422
+ cursor: "string",
423
+ captureWheel: "boolean",
424
+ fallback: "boolean",
425
+ },
426
+ events: { itemPress: "onItemPress" },
427
+ values: CATALOG_PROP_VALUES.Canvas,
428
+ defaults: { height: 360, cursor: "default" },
429
+ },
405
430
  {
406
431
  // Groups as soft circles with their members inside as bubbles, sized by `size`. `groups: [{ id?, label, color?,
407
432
  // nodes: [{ id, label, size? }] }]`; a node may sit in several groups. Not every host draws it: see `hostRenders`.
@@ -1,4 +1,4 @@
1
- export { PROTOCOL_VERSION, validateManifest, isSectionSlot, ManifestError, type PluginManifest, type Contribution, type ApiPermission, type HttpPermission, type HttpMethod, } from './manifest.js';
1
+ export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, type PluginManifest, type Contribution, type ApiPermission, type HttpPermission, type HttpMethod, } from './manifest.js';
2
2
  export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
3
3
  export { matchFixture, type Fixtures, type FixtureMatch } from './fixtures.js';
4
4
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, type WhenQuery, type ContextRoot, type Rollout, } from './when.js';
@@ -1,4 +1,4 @@
1
- export { PROTOCOL_VERSION, validateManifest, isSectionSlot, ManifestError, } from './manifest.js';
1
+ export { PROTOCOL_VERSION, validateManifest, validatePublishableManifest, unnamedContributions, contributionId, RESERVED_PLUGIN_ID, isSectionSlot, ManifestError, } from './manifest.js';
2
2
  export { isApiRequestAllowed, isHttpRequestAllowed, isRequestAllowed, normalizePath, canonicalizePath } from './allowlist.js';
3
3
  export { matchFixture } from './fixtures.js';
4
4
  export { CONTEXT_ROOTS, extractRoots, validateWhen, evaluateWhen, rolloutIncludes, WhenError, } from './when.js';
@@ -37,6 +37,11 @@ export interface PluginManifest {
37
37
  api?: ApiPermission[];
38
38
  http?: HttpPermission[];
39
39
  topics?: TopicPermissions;
40
+ /**
41
+ * Draws its own pixels with `Canvas`. Shown at install: inside its rectangle the plugin can paint anything,
42
+ * including something that looks like the host's own UI. It can't read the page or paint outside the rectangle.
43
+ */
44
+ canvas?: boolean;
40
45
  };
41
46
  contributes: Contribution[];
42
47
  }
@@ -46,3 +51,27 @@ export declare class ManifestError extends Error {
46
51
  export declare function isSectionSlot(slot: string): boolean;
47
52
  /** Validates an untrusted manifest object; throws `ManifestError` describing the first problem. */
48
53
  export declare function validateManifest(input: unknown): PluginManifest;
54
+ /** The platform's own blocks are `nullplatform/<block>`: no plugin may publish under that id (contract 5). */
55
+ export declare const RESERVED_PLUGIN_ID = "nullplatform";
56
+ /**
57
+ * The id a contribution goes by in block ids, flag keys and layouts: its `id`, or its widget for a revision published
58
+ * before ids were required (contract 5). One function, so every reader names an inherited contribution the same way.
59
+ */
60
+ export declare function contributionId(contribution: {
61
+ id?: string;
62
+ widget?: string;
63
+ }): string | undefined;
64
+ /**
65
+ * What a new revision must meet on top of `validateManifest` (contract 5): each contribution goes by a name unique in
66
+ * the manifest, since layouts, flags and section URLs point at it. The name is its `id` (lowercase letters, digits or
67
+ * dashes, 2-64 chars) or, without one, its widget, which is how hosts already keyed it. So a manifest that never
68
+ * repeats a widget stays publishable as it is, and one that mounts a widget twice must tell the two apart with ids.
69
+ * The plugin may not be `nullplatform`. The API applies it at publish and the CLI before uploading, so an author learns
70
+ * it before the build is pushed. Revisions published before keep working: hosts name them with `contributionId`.
71
+ */
72
+ export declare function validatePublishableManifest(input: unknown): PluginManifest;
73
+ /**
74
+ * Contributions that go by their widget for lack of an `id`. Publishable, but renaming the widget would rename the
75
+ * block, its flag and its place in layouts, so the CLI warns about them.
76
+ */
77
+ export declare function unnamedContributions(manifest: PluginManifest): string[];
@@ -100,6 +100,12 @@ export function validateManifest(input) {
100
100
  if (rawPermissions.topics !== undefined) {
101
101
  permissions.topics = readTopicPermissions(rawPermissions.topics, m.id);
102
102
  }
103
+ if (rawPermissions.canvas !== undefined) {
104
+ if (typeof rawPermissions.canvas !== 'boolean')
105
+ throw new ManifestError('permissions.canvas must be true or false');
106
+ if (rawPermissions.canvas)
107
+ permissions.canvas = true;
108
+ }
103
109
  return {
104
110
  protocol: PROTOCOL_VERSION,
105
111
  id: m.id,
@@ -149,3 +155,49 @@ function readTopicPermissions(raw, pluginId) {
149
155
  }
150
156
  return topics;
151
157
  }
158
+ /** The platform's own blocks are `nullplatform/<block>`: no plugin may publish under that id (contract 5). */
159
+ export const RESERVED_PLUGIN_ID = 'nullplatform';
160
+ /**
161
+ * The id a contribution goes by in block ids, flag keys and layouts: its `id`, or its widget for a revision published
162
+ * before ids were required (contract 5). One function, so every reader names an inherited contribution the same way.
163
+ */
164
+ export function contributionId(contribution) {
165
+ return contribution.id ?? contribution.widget;
166
+ }
167
+ /**
168
+ * What a new revision must meet on top of `validateManifest` (contract 5): each contribution goes by a name unique in
169
+ * the manifest, since layouts, flags and section URLs point at it. The name is its `id` (lowercase letters, digits or
170
+ * dashes, 2-64 chars) or, without one, its widget, which is how hosts already keyed it. So a manifest that never
171
+ * repeats a widget stays publishable as it is, and one that mounts a widget twice must tell the two apart with ids.
172
+ * The plugin may not be `nullplatform`. The API applies it at publish and the CLI before uploading, so an author learns
173
+ * it before the build is pushed. Revisions published before keep working: hosts name them with `contributionId`.
174
+ */
175
+ export function validatePublishableManifest(input) {
176
+ const manifest = validateManifest(input);
177
+ if (manifest.id === RESERVED_PLUGIN_ID)
178
+ throw new ManifestError(`Plugin id "${RESERVED_PLUGIN_ID}" is reserved for the platform's own blocks`);
179
+ // `validateManifest` drops an id that isn't a string; read the raw one so a malformed id is refused, not ignored.
180
+ const raw = input.contributes;
181
+ const seen = new Map();
182
+ manifest.contributes.forEach((contribution, index) => {
183
+ const id = raw[index]?.id;
184
+ if (id !== undefined && (typeof id !== 'string' || !ID_PATTERN.test(id))) {
185
+ throw new ManifestError(`contributes[${index}].id must be lowercase letters, digits or dashes (2-64 chars)`);
186
+ }
187
+ const name = contributionId(contribution);
188
+ const first = seen.get(name);
189
+ if (first !== undefined) {
190
+ const hint = contribution.id === undefined ? '; give each an id' : '';
191
+ throw new ManifestError(`contributes[${index}] goes by "${name}", already used by contributes[${first}]${hint}`);
192
+ }
193
+ seen.set(name, index);
194
+ });
195
+ return manifest;
196
+ }
197
+ /**
198
+ * Contributions that go by their widget for lack of an `id`. Publishable, but renaming the widget would rename the
199
+ * block, its flag and its place in layouts, so the CLI warns about them.
200
+ */
201
+ export function unnamedContributions(manifest) {
202
+ return manifest.contributes.flatMap((contribution, index) => (contribution.id === undefined ? [`contributes[${index}] (${contribution.widget})`] : []));
203
+ }
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assertTopicValue = exports.redactBySchema = exports.projectFields = exports.canProvideTopic = exports.consumeGrant = exports.isFieldPath = exports.topicOwner = exports.isHostTopic = exports.isTopicName = exports.TOPIC_VALUE_MAX_CHARS = exports.resolveAssetUrl = exports.validateStorageUrl = exports.PLUGIN_STORAGE_ORIGIN = exports.WhenError = exports.rolloutIncludes = exports.evaluateWhen = exports.validateWhen = exports.extractRoots = exports.CONTEXT_ROOTS = exports.matchFixture = exports.canonicalizePath = exports.normalizePath = exports.isRequestAllowed = exports.isHttpRequestAllowed = exports.isApiRequestAllowed = exports.ManifestError = exports.isSectionSlot = exports.validateManifest = exports.PROTOCOL_VERSION = void 0;
3
+ exports.assertTopicValue = exports.redactBySchema = exports.projectFields = exports.canProvideTopic = exports.consumeGrant = exports.isFieldPath = exports.topicOwner = exports.isHostTopic = exports.isTopicName = exports.TOPIC_VALUE_MAX_CHARS = exports.resolveAssetUrl = exports.validateStorageUrl = exports.PLUGIN_STORAGE_ORIGIN = exports.WhenError = exports.rolloutIncludes = exports.evaluateWhen = exports.validateWhen = exports.extractRoots = exports.CONTEXT_ROOTS = exports.matchFixture = exports.canonicalizePath = exports.normalizePath = exports.isRequestAllowed = exports.isHttpRequestAllowed = exports.isApiRequestAllowed = exports.ManifestError = exports.isSectionSlot = exports.RESERVED_PLUGIN_ID = exports.contributionId = exports.unnamedContributions = exports.validatePublishableManifest = exports.validateManifest = exports.PROTOCOL_VERSION = void 0;
4
4
  var manifest_1 = require("./manifest");
5
5
  Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return manifest_1.PROTOCOL_VERSION; } });
6
6
  Object.defineProperty(exports, "validateManifest", { enumerable: true, get: function () { return manifest_1.validateManifest; } });
7
+ Object.defineProperty(exports, "validatePublishableManifest", { enumerable: true, get: function () { return manifest_1.validatePublishableManifest; } });
8
+ Object.defineProperty(exports, "unnamedContributions", { enumerable: true, get: function () { return manifest_1.unnamedContributions; } });
9
+ Object.defineProperty(exports, "contributionId", { enumerable: true, get: function () { return manifest_1.contributionId; } });
10
+ Object.defineProperty(exports, "RESERVED_PLUGIN_ID", { enumerable: true, get: function () { return manifest_1.RESERVED_PLUGIN_ID; } });
7
11
  Object.defineProperty(exports, "isSectionSlot", { enumerable: true, get: function () { return manifest_1.isSectionSlot; } });
8
12
  Object.defineProperty(exports, "ManifestError", { enumerable: true, get: function () { return manifest_1.ManifestError; } });
9
13
  var allowlist_1 = require("./allowlist");
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ManifestError = exports.PROTOCOL_VERSION = void 0;
3
+ exports.RESERVED_PLUGIN_ID = exports.ManifestError = exports.PROTOCOL_VERSION = void 0;
4
4
  exports.isSectionSlot = isSectionSlot;
5
5
  exports.validateManifest = validateManifest;
6
+ exports.contributionId = contributionId;
7
+ exports.validatePublishableManifest = validatePublishableManifest;
8
+ exports.unnamedContributions = unnamedContributions;
6
9
  const when_1 = require("./when");
7
10
  const topics_1 = require("./topics");
8
11
  exports.PROTOCOL_VERSION = 1;
@@ -106,6 +109,12 @@ function validateManifest(input) {
106
109
  if (rawPermissions.topics !== undefined) {
107
110
  permissions.topics = readTopicPermissions(rawPermissions.topics, m.id);
108
111
  }
112
+ if (rawPermissions.canvas !== undefined) {
113
+ if (typeof rawPermissions.canvas !== 'boolean')
114
+ throw new ManifestError('permissions.canvas must be true or false');
115
+ if (rawPermissions.canvas)
116
+ permissions.canvas = true;
117
+ }
109
118
  return {
110
119
  protocol: exports.PROTOCOL_VERSION,
111
120
  id: m.id,
@@ -155,3 +164,49 @@ function readTopicPermissions(raw, pluginId) {
155
164
  }
156
165
  return topics;
157
166
  }
167
+ /** The platform's own blocks are `nullplatform/<block>`: no plugin may publish under that id (contract 5). */
168
+ exports.RESERVED_PLUGIN_ID = 'nullplatform';
169
+ /**
170
+ * The id a contribution goes by in block ids, flag keys and layouts: its `id`, or its widget for a revision published
171
+ * before ids were required (contract 5). One function, so every reader names an inherited contribution the same way.
172
+ */
173
+ function contributionId(contribution) {
174
+ return contribution.id ?? contribution.widget;
175
+ }
176
+ /**
177
+ * What a new revision must meet on top of `validateManifest` (contract 5): each contribution goes by a name unique in
178
+ * the manifest, since layouts, flags and section URLs point at it. The name is its `id` (lowercase letters, digits or
179
+ * dashes, 2-64 chars) or, without one, its widget, which is how hosts already keyed it. So a manifest that never
180
+ * repeats a widget stays publishable as it is, and one that mounts a widget twice must tell the two apart with ids.
181
+ * The plugin may not be `nullplatform`. The API applies it at publish and the CLI before uploading, so an author learns
182
+ * it before the build is pushed. Revisions published before keep working: hosts name them with `contributionId`.
183
+ */
184
+ function validatePublishableManifest(input) {
185
+ const manifest = validateManifest(input);
186
+ if (manifest.id === exports.RESERVED_PLUGIN_ID)
187
+ throw new ManifestError(`Plugin id "${exports.RESERVED_PLUGIN_ID}" is reserved for the platform's own blocks`);
188
+ // `validateManifest` drops an id that isn't a string; read the raw one so a malformed id is refused, not ignored.
189
+ const raw = input.contributes;
190
+ const seen = new Map();
191
+ manifest.contributes.forEach((contribution, index) => {
192
+ const id = raw[index]?.id;
193
+ if (id !== undefined && (typeof id !== 'string' || !ID_PATTERN.test(id))) {
194
+ throw new ManifestError(`contributes[${index}].id must be lowercase letters, digits or dashes (2-64 chars)`);
195
+ }
196
+ const name = contributionId(contribution);
197
+ const first = seen.get(name);
198
+ if (first !== undefined) {
199
+ const hint = contribution.id === undefined ? '; give each an id' : '';
200
+ throw new ManifestError(`contributes[${index}] goes by "${name}", already used by contributes[${first}]${hint}`);
201
+ }
202
+ seen.set(name, index);
203
+ });
204
+ return manifest;
205
+ }
206
+ /**
207
+ * Contributions that go by their widget for lack of an `id`. Publishable, but renaming the widget would rename the
208
+ * block, its flag and its place in layouts, so the CLI warns about them.
209
+ */
210
+ function unnamedContributions(manifest) {
211
+ return manifest.contributes.flatMap((contribution, index) => (contribution.id === undefined ? [`contributes[${index}] (${contribution.widget})`] : []));
212
+ }
package/dist/index.d.ts CHANGED
@@ -5,5 +5,6 @@ export { nullplatform, type NullplatformBridge } from './bridge.js';
5
5
  export { useTopic, useSetTopic, type UseTopicOptions, type UseTopicResult, type UseSetTopicOptions, type SetTopicState, type TopicMap, type ServiceDraftV1, } from './topics.js';
6
6
  export * from './components.js';
7
7
  export { hostRenders } from './host.js';
8
+ export { Canvas, useCanvas, canDrawCanvas, type CanvasProps, type CanvasHandle, type CanvasOptions, type CanvasFrame, type CanvasItem, type CanvasInput, type CanvasTheme, type CanvasTooltip, } from './canvas.js';
8
9
  export type { PluginContext, ApiRequest, HttpRequest, HttpResponse, NavigationTarget, SnackbarOptions, ConfirmOptions, TopicSnapshot, TopicStatus } from './protocol.js';
9
10
  export { BridgeError } from './protocol.js';
package/dist/index.js CHANGED
@@ -5,4 +5,5 @@ export { nullplatform } from './bridge.js';
5
5
  export { useTopic, useSetTopic, } from './topics.js';
6
6
  export * from './components.js';
7
7
  export { hostRenders } from './host.js';
8
+ export { Canvas, useCanvas, canDrawCanvas, } from './canvas.js';
8
9
  export { BridgeError } from './protocol.js';
@@ -158,11 +158,81 @@ export interface TopicSnapshot<T = unknown> {
158
158
  /** Increases on every change, so a late reply never overwrites a newer value. */
159
159
  rev: number;
160
160
  }
161
+ /** The host theme as a canvas draws it: resolved colors, so the plugin never reads the host's styles. */
162
+ export interface CanvasTheme {
163
+ mode: 'light' | 'dark';
164
+ /** The page and the card the canvas sits on. */
165
+ background: string;
166
+ surface: string;
167
+ text: string;
168
+ textSecondary: string;
169
+ divider: string;
170
+ primary: string;
171
+ success: string;
172
+ warning: string;
173
+ error: string;
174
+ /** Categorical colors for groups that aren't states, in order. */
175
+ palette: string[];
176
+ fontFamily: string;
177
+ }
178
+ interface CanvasModifiers {
179
+ shift: boolean;
180
+ alt: boolean;
181
+ ctrl: boolean;
182
+ meta: boolean;
183
+ }
184
+ /** Input on a canvas, in CSS pixels from its top left corner. */
185
+ export type CanvasInput = ({
186
+ kind: 'down' | 'move' | 'up' | 'leave';
187
+ x: number;
188
+ y: number;
189
+ button: number;
190
+ buttons: number;
191
+ } & CanvasModifiers) | ({
192
+ kind: 'wheel';
193
+ x: number;
194
+ y: number;
195
+ dx: number;
196
+ dy: number;
197
+ } & CanvasModifiers) | ({
198
+ kind: 'key';
199
+ key: string;
200
+ } & CanvasModifiers);
201
+ /** A tooltip the host draws over the canvas with its own components, anchored at `x`, `y` (CSS pixels). */
202
+ export interface CanvasTooltip {
203
+ x: number;
204
+ y: number;
205
+ title: string;
206
+ rows?: Array<{
207
+ label: string;
208
+ value: string;
209
+ }>;
210
+ }
161
211
  export type WorkerMessage = {
162
212
  type: 'ready';
163
213
  protocol: number;
164
214
  pluginId: string;
165
215
  widgets: string[];
216
+ }
217
+ /**
218
+ * A drawn frame for a canvas surface, transferred rather than cloned. `seq` is the last input the plugin had
219
+ * handled when it drew, which is how the host paces the pointer moves it sends.
220
+ */
221
+ | {
222
+ type: 'canvas-frame';
223
+ surface: string;
224
+ bitmap: ImageBitmap;
225
+ seq: number;
226
+ }
227
+ /** The plugin handled input `seq` without drawing. */
228
+ | {
229
+ type: 'canvas-ack';
230
+ surface: string;
231
+ seq: number;
232
+ } | {
233
+ type: 'canvas-overlay';
234
+ surface: string;
235
+ tooltip: CanvasTooltip | null;
166
236
  } | {
167
237
  type: 'mutate';
168
238
  mountId: string;
@@ -224,6 +294,20 @@ export type HostMessage =
224
294
  } | {
225
295
  type: 'topic';
226
296
  snapshot: TopicSnapshot;
297
+ }
298
+ /** The surface's size in CSS pixels, the device pixel ratio to draw at and the theme; sent again on every change. */
299
+ | {
300
+ type: 'canvas-size';
301
+ surface: string;
302
+ width: number;
303
+ height: number;
304
+ dpr: number;
305
+ theme: CanvasTheme;
306
+ } | {
307
+ type: 'canvas-input';
308
+ surface: string;
309
+ seq: number;
310
+ input: CanvasInput;
227
311
  };
228
312
  export interface SerializedError {
229
313
  message: string;
@@ -258,3 +342,4 @@ export declare function createIdGenerator(prefix: string): () => string;
258
342
  export declare function assertWireValue(value: unknown): void;
259
343
  /** Deadline also covers custom adapters/loaders that ignore cancellation. */
260
344
  export declare function withDeadline<T>(promise: Promise<T>, timeoutMs?: number, signal?: AbortSignal): Promise<T>;
345
+ export {};
package/dist/worker.js CHANGED
@@ -11,6 +11,7 @@ import { bridge } from './bridge.js';
11
11
  import { PluginContextProvider, broadcastContext } from './context.js';
12
12
  import { setHostElements } from './host.js';
13
13
  import { receiveTopic } from './topics.js';
14
+ import { attachCanvasPort, receiveCanvas } from './canvas.js';
14
15
  import { PROTOCOL_VERSION, createIdGenerator, serializeError, serializeFunctions, } from './protocol.js';
15
16
  const nextFunctionId = createIdGenerator('fn');
16
17
  const mounts = new Map();
@@ -113,6 +114,10 @@ function handle(port, message) {
113
114
  case 'topic':
114
115
  receiveTopic(message.snapshot);
115
116
  break;
117
+ case 'canvas-size':
118
+ case 'canvas-input':
119
+ receiveCanvas(message);
120
+ break;
116
121
  default:
117
122
  break;
118
123
  }
@@ -125,6 +130,7 @@ function handle(port, message) {
125
130
  /** Connects this worker to the host through the port handed over by the sandbox. */
126
131
  export function connect(port) {
127
132
  bridge.attach(port);
133
+ attachCanvasPort(port);
128
134
  globalThis.addEventListener('unhandledrejection', (event) => {
129
135
  port.postMessage({ type: 'error', error: serializeError(event.reason) });
130
136
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullplatform/ui-plugin-sdk",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "SDK for nullplatform UI plugins: catalog components, bridge client and defineUI",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",