2026-12-01 09:29:18 +01:00

@wavepath/plugin-sdk

The plugin-author guide and toolkit for WavePath web extensions. With it, a Winter plugin can add UI to the WavePath SPA without anyone editing the SPA itself.

The package contains:

  • The TypeScript contract (types/index.d.ts): the types for window.registerPlugin, the registry, the host API and the slot contexts.
  • The runtime contract constants (@wavepath/plugin-sdk/contract). The host is checked against them.
  • A Vite helper (@wavepath/plugin-sdk/vite). It builds your bundle as one IIFE over the host's Vue.
  • A Tailwind v4 host preset (@wavepath/plugin-sdk/theme.css).

Install it by git tag:

npm install -D --allow-git=root "@wavepath/plugin-sdk@git+https://git.golem15.com/jakub/wavepath-plugin-sdk.git#v1.2.0"

npm 12 refuses git dependencies by default (EALLOWGIT). Add allow-git=root to your project's .npmrc, so plain npm install / npm ci keep working for you and your CI. Older npm versions ignore the setting.


What a plugin can ship

A plugin can contribute to the SPA in two ways. It can use either one, or both:

  1. Declarative message actions. The plugin declares them in PHP. The SPA renders them generically on desktop (3-dot menu, with submenus) and on mobile (flat sheet rows, plus the destructive zone with a confirm step). No JavaScript is needed.
  2. A JS bundle. A classic script (main.js, optionally with main.css) that calls window.registerPlugin(...) and registers custom UI, predicates, icons and realtime handlers.

Both paths feed one runtime registry. A declarative action can use a predicate that the same plugin's bundle registers.

The same registerWebExtensions() declaration can also carry:

  • Inline media hosts (inlineMedia). Links to a media host you declare render inline in every chat surface, loaded straight from that host in the viewer's browser, and the server never fetches them. See Inline media hosts.
  • Plugin config (config). A small, public settings object your bundle reads with useConfig(). See Plugin config.

How plugins are enabled and trusted:

  • Installed means loaded. If a plugin is installed and enabled on the server and declares web extensions, it is active for every signed-in user. There is no admin toggle and no per-group switch. Installing the plugin is the trust decision.
  • Signed-in users only. Guests and public pages never get plugin actions or bundles.
  • Bundle JS has full page access. It runs in the page, with the user's session. Treat a bundle like any other code you deploy to production.

Declarative message actions

Add a registerWebExtensions() method to your Plugin.php. The host discovers it on enabled plugins only.

public function registerWebExtensions(): array
{
    return [
        'apiVersion' => 1,
        // Optional: only when the plugin also ships a bundle. Paths are relative to the plugin dir.
        'bundle' => ['js' => 'assets/webapp/main.js', 'css' => 'assets/webapp/main.css'],
        'messageActions' => [[
            'id' => 'capture',
            'label' => 'author.plugin::lang.web.menu',
            'icon' => 'camera',
            'items' => [
                [
                    'id' => 'single',
                    'value' => 'main-tweet',
                    'icon' => 'message-square-text',
                    'label' => 'author.plugin::lang.web.mode.single',
                    'mobileLabel' => ['author.plugin::lang.web.row', ['mode' => 'author.plugin::lang.web.mode.single']],
                    'visibleWhen' => ['predicate' => 'capturable'],
                    'endpoint' => '/_wave/api/v1/author-plugin/web-actions/capture',
                ],
                [
                    'id' => 'remove',
                    'value' => null,
                    'icon' => 'image-off',
                    'label' => 'author.plugin::lang.web.remove.action',
                    'destructive' => true,
                    'separatorBefore' => true,
                    'visibleWhen' => ['all' => [
                        ['any' => [['isOwn' => true], ['canModerate' => true]]],
                        ['metaPresent' => 'capture.id'],
                    ]],
                    'confirm' => [
                        'title' => 'author.plugin::lang.web.remove.title',
                        'body' => 'author.plugin::lang.web.remove.body',
                        'confirm' => 'author.plugin::lang.web.remove.confirm',
                        'cancel' => 'author.plugin::lang.web.remove.keep',
                    ],
                    'endpoint' => '/_wave/api/v1/author-plugin/web-actions/remove',
                ],
            ],
        ]],
    ];
}

Action and item keys

Key Meaning
id Stable id, unique within the plugin. The host namespaces it as <Author.Plugin>/<id>.
label A lang key, or [key, replacements]. Replacement values may be lang keys themselves.
mobileLabel The label of the flat mobile row. If you omit it, it defaults to "{label}: {item label}".
icon A lucide kebab-case name: one of the host's built-in icons (HOST_ICON_NAMES), or one your bundle registered with registerIcon. An unknown name renders no icon.
items Submenu items with the same keys, without items. The desktop menu shows a submenu; mobile shows one flat row per item.
value Sent to the endpoint as value. Use null when there is nothing to choose.
endpoint The POST endpoint. It must start with /_wave/api/v1/.
destructive Desktop renders the item in the danger style. Mobile moves it into the destructive zone above Delete.
separatorBefore Draws a separator above the item on desktop.
visibleWhen A rule (see below). If you omit it, the item is always shown, subject to the host preconditions.
confirm {title, body, confirm, cancel} lang keys. The host shows a confirm dialog (desktop) or sheet (mobile) before calling.

All labels are resolved on the server for the locale the SPA asks for (?locale=pl|en). When the user switches language, the SPA refetches the list.

The server validates every declaration. An invalid action is dropped and a warning naming the plugin and the reason is logged. The rest of the list still works, so one broken declaration never breaks other plugins.

Visibility rules (visibleWhen)

A rule is an array with exactly one key. The SPA evaluates rules on the client, with no round trip.

Rule True when
['all' => [rule, ...]] every rule is true (AND)
['any' => [rule, ...]] at least one rule is true (OR)
['isOwn' => true] the current user wrote the message
['canModerate' => true] the current user can moderate the conversation
['attachmentKind' => 'image'] the message has an attachment of that kind (image, video, audio, file)
['textMatches' => ['pattern' => '...', 'flags' => 'i']] the message text matches the JavaScript regex. Flags are limited to i, m, s, u. An invalid pattern makes the rule false.
['metaPresent' => 'a.b'] the dotted path exists in message.metadata and is not null
['predicate' => 'name'] a predicate that the same plugin's bundle registered with registerPredicate('name', fn) returns true. An unknown or not-yet-loaded predicate is false, so the item stays hidden until the bundle registers it.

Rules nest up to 4 levels deep. There is no not: anything the grammar cannot express belongs in a bundle predicate.

Host preconditions. These apply to every declarative item, whatever its rules say. The message must be saved (it has a real id), must not still be sending, and must not be deleted.

Rules decide what is shown, not what is allowed. They run in the browser, so anyone can bypass them. Your endpoint must check the actor (from the JWT, never from the body) and its rights itself, exactly as if the rule did not exist.


The action endpoint contract

When the user picks a declarative item, the SPA POSTs to its endpoint with the user's normal cookie auth. The body is exactly:

{ "message_id": 123, "conversation_id": 45, "value": "main-tweet", "locale": "pl" }

Your endpoint should reject a conversation_id that does not match the message. Reply with Golem15\WavePath\Classes\WebExtensions\WebActionResponse. It produces the shape the SPA understands: the optional toast sits next to data.

use Golem15\WavePath\Classes\WebExtensions\WebActionResponse;

return WebActionResponse::ok(['status' => 'queued'], ['type' => 'success', 'text' => Lang::get('author.plugin::lang.web.queued', [], $locale)]);

return WebActionResponse::fail(404, ['type' => 'error', 'text' => Lang::get('author.plugin::lang.web.gone', [], $locale)]);
  • ok(array $data = [], ?array $toast = null) answers 200 {data, toast?}.
  • fail(int $status, ?array $toast = null, string $message = 'Action failed.') answers {error: true, message, code: "ACTION_FAILED", toast?}.
  • A toast is {type: success|error|info, text}. Localise the text on the server, using the locale from the request body.
  • If there is no toast, the SPA stays silent on success. On a non-2xx response without a toast, it shows its generic error toast.
  • Never optimistic. If the action changes the message, the change reaches every client through the existing realtime edited frame, and the SPA refetches the message. The SPA does not patch the message from your response.

Inline media hosts

A plugin that lets users post media from a third-party host (a GIF provider, for example) declares that host. The core then renders matching links inline instead of as a link card:

public function registerWebExtensions(): array
{
    return [
        'apiVersion' => 1,
        'inlineMedia' => [[
            'id' => 'media',
            'host' => 'media.example.com',
            'pathPattern' => '^/m/[A-Za-z0-9_-]+\\.gif$',
            'kind' => 'gif',
        ]],
    ];
}

The server validates each entry exactly as follows. An invalid entry is dropped with a server warning naming the plugin and the reason; valid sibling entries and the rest of the declaration survive.

Key Rule
id ^[a-z0-9-]{1,40}$, unique within the plugin.
host An exact, lowercase DNS name (media.example.com). https only. No wildcard, no port, no IP literal, at least two labels. A link matches only when its host equals this value exactly (case-insensitive on the link side); subdomains do not match.
pathPattern 1–200 characters. Matched against the URL path only (no query, no fragment). It is a search, not a full match, so anchor it with ^…$. See the regex rules below.
kind gif (the only kind today).

At most 5 entries per plugin; extra entries are dropped with a warning.

Regex rules. The pattern runs twice: as PCRE (flags u and D) on the server and as a JavaScript RegExp with the u flag in every viewer's browser, where nothing limits backtracking. So the server accepts only a small, safe grammar. Every accepted pattern reads the same in PCRE and in a JavaScript u-flag RegExp; anything else is dropped with a warning (inlineMedia #N dropped: <reason>). The allowed syntax:

  • Anchors only at the ends: an optional ^ as the first character and an optional $ as the last.
  • Literals: any printable ASCII character except \ ^ $ . | ? * + ( ) [ ] { }. No spaces, no non-ASCII.
  • ., \d, \w, and a backslash before one of the syntax characters ^ $ \ . * + ? ( ) [ ] { } | /. No other escape (\s, \b, \z, \#, \- outside a class, \1, \k<…>, \p{…}, …).
  • Character classes […] and [^…] of literals, the escapes above, \-, and ranges x-y with single-character ends (a-z, never \w-x). A ] may not come right after [ or [^ (write \]), and an unescaped [ inside a class is rejected (no POSIX [[:alpha:]]). A leading or trailing - is a literal.
  • Quantifiers ? * + {n} {n,} {n,m} (n ≤ m ≤ 255, at least one repetition allowed) on a single atom only, never lazy (+?) or possessive (++).
  • Groups (…) or (?:…) holding |-separated alternatives of plain atoms (no quantifier, no nested group inside), optionally followed by ?. No other quantifier on a group, no | outside a group, and no other (?… form (no flags, lookaround, named or atomic groups, no (*VERB)).

Determinism rule. A repeated or optional part must not be able to match the character that follows it, and the alternatives of a group must start with different characters. [^/]+/ is fine, .+\.gif is rejected (write [^.]+\.gif); (gif|webp) is fine, (a|ab) is rejected; [a-z]*[a-z]* is rejected. This keeps matching linear, so no pattern can freeze a viewer's tab.

The tested URL path is at most 256 characters. A link on your declared host with a longer path never renders inline, and the server never fetches it either: it stays a plain link with no preview. A pattern that fails at match time on the server (for example, the PCRE backtrack limit) counts as no inline match, and the server does not fetch that link. Keep patterns simple and anchored: a fixed prefix plus one character class is all a media URL needs.

What a declaration does:

  • The server never fetches a matching link, or any link on your declared host whose path is longer than 256 characters. No unfurl job is queued, so no request to your host ever leaves the WavePath server. This holds for every send path (chat, DMs, channels, bots, webhooks). Other links on the same host still get the usual link card.
  • Matching links render inline in every chat surface, loaded directly from the declared host in the viewer's browser. Links on any other host keep the usual proxied link card.
  • Guests see a plain link. The declared host list comes with the signed-in plugin list, so the guest call chat never receives it.
  • Declare inlineMedia even when your feature is switched off, so media users already posted keeps rendering.

Render hints

An inline-media URL may carry a provider-neutral fragment that tells the host how to show it:

https://media.example.com/m/Ab12Cd34.gif#w=498&h=280&v=Xy98Zw76.mp4
Hint Meaning
w, h Integers 1–4096. The host reserves the media box from them before the media loads, so the chat does not jump. The host caps the box to 300×300 and clamps the aspect ratio between 1:3 and 3:1.
v A bare filename matching ^[A-Za-z0-9_-]{1,64}\.(mp4|webm)$. It is resolved relative to the URL's own directory (https://media.example.com/m/Xy98Zw76.mp4 above) and re-checked against the same declared rule, so it can never point anywhere your declaration does not allow. The host plays it as a muted, looping, inline video and falls back to an image of the URL itself.
  • The fragment is never sent to any server: browsers strip it from requests.
  • A missing or invalid hint degrades gracefully: the host shows the URL as an image in a fixed-size box.
  • Unknown hint keys are ignored, so the grammar can grow additively.

Plugin config

config is an associative array that the host passes verbatim to your bundle, which reads it with useConfig():

'config' => ['apiKey' => $publicClientKey, 'contentFilter' => Settings::get('content_filter', 'medium')],
import { useConfig } from '@wavepath/plugin-sdk'

const config = useConfig() // Readonly<Ref<Readonly<Record<string, unknown>> | null>>
const filter = computed(() => String(config.value?.contentFilter ?? 'medium'))

Limits, enforced by the server:

  • JSON-encodable: scalar or null leaves, or lists of scalars (no objects or resources);
  • at most 4096 bytes once JSON-encoded;
  • nesting depth at most 3.

An invalid value is dropped to null with a server warning. The warning names the reason, never a config value, and the plugin itself is kept. [] and an absent key both mean null.

  • It is public. config is sent to every signed-in browser, so never put a server secret in it. A client-side API key that the provider issues for browser use is fine; a server credential is not.
  • It is live. The server re-reads it on every list request, so a value backed by an admin setting shows up after the next list refetch, without a rebuild or a re-pin.

Bundles

A bundle is a single classic script that calls window.registerPlugin:

// webapp/src/main.ts
import type { PluginDefinition } from '@wavepath/plugin-sdk'
import { useT } from '@wavepath/plugin-sdk'
import { defineComponent, h } from 'vue'
import en from './lang/en.json'
import pl from './lang/pl.json'

const plugin: PluginDefinition = {
  apiVersion: 1,
  messages: { en, pl },
  initialize(registry, host) {
    registry.registerPredicate('capturable', ({ message }) => /x\.com\//.test(message.content ?? ''))
    registry.registerMessageAction({
      id: 'hello',
      desktop: defineComponent({
        props: ['ctx'],
        setup(props) {
          const t = useT()
          return () =>
            h(host.components.DropdownMenuItem, { onSelect: () => host.toast.notify(t('hello')) }, () => t('menu'))
        },
      }),
    })
  },
  uninitialize() {
    // Release anything initialize() created outside the registry (timers, listeners).
  },
}

window.registerPlugin('Author.Plugin', plugin)
  • The id passed to registerPlugin is the Winter plugin code (Author.Plugin). In production the host only accepts it from the script tag it inserted for that plugin, and refuses a second registration of an id.
  • apiVersion is a handshake. The host supports a version range (HOST_API_VERSION_RANGE, currently 1–1) and refuses a bundle outside it. The refusal is reported as an apiVersion error.
  • initialize(registry, host) may run more than once per page. Logout clears all registrations in place (without a reload) and calls uninitialize(). The next sign-in calls initialize() again on the cached definition, without loading the script again. Keep initialize idempotent, and keep per-session state inside it. If initialize returns a promise, it must settle within 5 s.
  • Every register* call returns an unregister function. If initialize throws, the host rolls back everything the plugin registered.

Registry (initialize's first argument)

Method Contributes
registerMessageAction(item) A message action: {id, desktop, mobile?, mobileDestructive?, showsDestructive?(ctx), desktopOverlay?, mobileOverlay?}. The components get the ctx prop (MessageActionContext: message, isOwn, canModerate, closeMenu(), openOverlay(id)). Overlays also get open and emit update:open.
registerComposerAction(item) A composer action-row button: {id, icon, tooltip, onClick?(ctx), component?}
registerSettingsSection(item) A per-user settings section rendered inside a host card on Settings → Plugins: {id, title, description?, icon?, component, diaryOnly?}. Since 1.4.0.
registerWebSocketEventHandler(fn) fn({channel, event, payload}) for every frame on the channels the host already subscribes to. Plugins never open their own socket.
registerPredicate(name, fn) A predicate that declarative rules can use as {predicate: name}. fn({message, isOwn, canModerate}) must return a boolean, synchronously.
registerIcon(name, component) An icon that declarative actions can name

Host API (initialize's second argument, also importable)

The same object is exported by @wavepath/plugin-sdk, so import { useT, toast } from '@wavepath/plugin-sdk' works inside components. Its keys are exactly HOST_SDK_KEYS:

Key What it is
components The host UI kit: Button, Input, Switch, DropdownMenu* (including the Sub* parts), Popover, PopoverTrigger, PopoverContent, Sheet*, AlertDialog*, Dialog* (see HOST_COMPONENT_KEYS)
icons The built-in lucide icons (see HOST_ICON_NAMES; this list only ever grows)
toast success(text), error(text), notify(text)
api The host's authenticated HTTP client: get(url, config?), post(url, body?, config?), put, patch, delete(url, config?). Each resolves to {data, status} and rejects on a non-2xx response.
useCurrentUser() A read-only ref holding {id, name, avatar}, or null
useLocale() A read-only ref holding 'pl' or 'en'
useT() A scoped translator: t('menu') resolves plugins.<author>.<name>.menu from your messages
usePluginId() Your plugin id
getMeta(message, 'a.b') Reads a nested message.metadata value. metadata is typed `object
useConfig() A read-only ref holding your plugin's config (see Plugin config), or null when you declare none. It updates when the host refetches the plugin list. Since 1.2.0.
useShell() A read-only ref holding 'desktop' or 'mobile': the host chat shell, from the host's single md breakpoint (768px). Never derived from the user agent. Since 1.2.0.

UI-kit notes (1.2.0):

  • Popover, PopoverTrigger, PopoverContent are the host's reka-based popover. PopoverContent is portalled to <body> with a z-index above the composer, so it is not clipped by the chat layout. Forward @close-auto-focus (and call preventDefault() on it) when you want focus to stay where you put it, for example back in the composer after a pick.
  • The host Sheet closes on the Android back gesture when you bind its open state with v-model:open. The back gesture then dismisses the sheet instead of leaving the page. An uncontrolled sheet does not get this.
  • A common pattern: useShell() picks a Popover on desktop and a bottom Sheet on mobile.

Rules for using the host API:

  • Internal stores are not API. The host's Pinia stores (chat, community, auth, ...), its router and its other internals are deliberately not exposed, and may change at any time. Use only the slot contexts and the host API.
  • Don't bundle a second copy of a host library. Vue, Pinia and the SDK come from the host as externals. Do not bundle vue-i18n, reka-ui or the host UI kit: a second copy breaks Vue injection. Use useT() and host.components instead.
  • Translations. messages: {en, pl} is merged under plugins.<author>.<name> (lowercase), so useT()('menu') follows the user's language exactly like host strings do. Declarative labels do not use these messages; the server resolves them (see above).
  • Realtime frames carry no content. They contain ids and an event name only, never message text. When a frame tells you something changed, refetch over REST with api.
  • Handle your own promise rejections. The host wraps every call into your code (initialize, predicates, handlers, onClick, renders) and catches what it throws. It cannot catch a promise you start and leave floating, so catch those rejections yourself.
  • Contract constants (PLUGIN_API_VERSION, HOST_ICON_NAMES, ...) come from @wavepath/plugin-sdk/contract, never from the main entry: at runtime the main entry is the host object.

Styling

Your bundle builds its own CSS with Tailwind v4 over the host's design tokens. In webapp/src/main.css:

@import "@wavepath/plugin-sdk/theme.css";

Then import ./main.css from main.ts. theme.css brings in Tailwind's theme as a reference only and the utilities layer, and maps the host tokens. So bg-primary compiles to background-color: var(--primary) and follows the host theme. The built main.css holds utilities only: no preflight reset and no :root variables.

  • Never @import "tailwindcss" in a plugin. It re-injects preflight and the default theme variables after the host CSS, and overrides the host everywhere.
  • Prefer composing host.components, which are already styled. Use utilities for layout and small touches.
  • If your bundle has no styles, leave out bundle.css.

Theme tokens

Users pick a theme (WavePath Black, Denim, Sapphire, Quartz, Indigo, or their own Custom theme), and the host rewrites its CSS variables on <html> to match. A plugin follows every theme with no host edit as long as it only uses these token names through the Tailwind utilities theme.css maps (bg-<token>, text-<token>, border-<token>, with opacity modifiers such as bg-scrim/55).

Light themes exist since 1.1.0 (Denim, Sapphire and Quartz have white content areas). Never hard-code white, black, Tailwind palette colours (bg-red-600, text-white, bg-emerald-500, …) or hex values: they break on one theme or the other. The .dark class on <html> follows the active theme's light/dark scheme, so dark: variants still work.

This is the whole plugin token contract. The values in the table are the WavePath Black defaults.

Token Role WavePath Black
background Page and content background #020202
foreground Body text #C8CBCF
card / card-foreground Cards, sheets, dialogs and their text #1E2226 / #C8CBCF
popover / popover-foreground Dropdowns, popovers and their text #1E2226 / #C8CBCF
muted / muted-foreground Inset fills, skeletons / secondary and meta text #272C30 / #AEAEAE
secondary / secondary-foreground Secondary buttons #272C30 / #C8CBCF
accent / accent-foreground Hover fills / heading-tone text #272C30 / #E6E8EA
border Dividers and input borders #383E43
input Field fills #272C30
ring Focus rings #DAA520
primary / primary-foreground Primary buttons, selected states / text on them #DAA520 / #16191C
primary-hover / primary-pressed Primary hover and pressed fills #FFDF00 / #D39E00
destructive / destructive-foreground Destructive actions, errors / text on them #E5484D / #FFFFFF
info / info-foreground Informational pills (not themed) #2F6FEB / #FFFFFF
rail / rail-foreground / rail-hover App rail and bottom nav / its items / item hover #1E2226 / #AEAEAE / #272C30
nav / nav-foreground Channel sidebar / read channel names #020202 / #C8CBCF
nav-muted / nav-hover Muted channels / sidebar row hover #AEAEAE / #111314
nav-active Active indicator, unread dots and badges #DAA520
nav-active-bg / nav-active-foreground Active row fill / active channel name #272C30 / #E6E8EA
nav-active-contrast Text on nav-active fills #16191C
nav-unread Unread channel names #E6E8EA
nav-drawer Mobile channel drawer surface #1E2226
link / link-hover Links in text #DAA520 / #FFDF00
separator-new / separator-new-label "New messages" divider line / its label #DAA520 / #DAA520
status-online / status-away / status-dnd Presence: online, away, do not disturb #10B981 / #F59E0B / #DAA520
mention / mention-foreground Mention and unread count badges / their text #DC2626 / #FFFFFF
success / success-foreground Saved and success states / text on them #059669 / #FFFFFF
scrim Overlays behind dialogs and media (use with an alpha, e.g. bg-scrim/55) #000000
media / on-media Image and video letterbox / text and controls over media #000000 / #FFFFFF

theme.css also maps the host fonts (font-sans, font-display, font-heading) and radii (rounded-sm … rounded-xl).

Not part of the contract: the raw theme keys users edit (railBg, navBg, buttonBg, …), and the host's internal --code-* (code-block palette) and --nav-mention* variables. They can change without a version bump, so never read them from a plugin.


Build

webapp/package.json:

{
  "private": true,
  "type": "module",
  "scripts": { "build": "vite build", "dev": "vite", "verify": "node scripts/verify-build.mjs" },
  "devDependencies": {
    "@wavepath/plugin-sdk": "git+https://git.golem15.com/jakub/wavepath-plugin-sdk.git#v1.2.0",
    "@vitejs/plugin-vue": "~6.0.7",
    "@tailwindcss/vite": "~4.3.0",
    "tailwindcss": "~4.3.0",
    "typescript": "~5.9.3",
    "vite": "~7.3.3",
    "vue": "~3.5.34"
  }
}

webapp/vite.config.ts:

import { defineWavePathPlugin } from '@wavepath/plugin-sdk/vite'
import tailwindcss from '@tailwindcss/vite'

export default defineWavePathPlugin({ id: 'Author.Plugin', plugins: [tailwindcss()] })

defineWavePathPlugin({ id, entry = 'src/main.ts', outDir = '../assets/webapp', plugins = [], vue = true }):

  • builds one classic IIFE, ../assets/webapp/main.js, plus main.css when the bundle has styles;
  • keeps vue, pinia and @wavepath/plugin-sdk external, mapped to the globals WavePath.Vue, WavePath.Pinia and WavePath.sdk, so your bundle never contains Vue;
  • replaces process.env.NODE_ENV, because a browser IIFE has no process;
  • produces deterministic output: the same source gives byte-identical files.

Next to it, webapp/.npmrc holds allow-git=root (see the install note at the top).

Run npm run build and commit the built assets/webapp/ files. The server deploy needs no Node, and the pin step hashes exactly what you committed. Also commit package-lock.json. It records the SDK commit your tag resolved to.

Add a verify script, scripts/verify-build.mjs. It should rebuild into a temporary directory and byte-compare the result with ../assets/webapp/*, exiting 1 on any difference. Run it in CI or before you tag, so the committed build always matches the source.


Pin and deploy

The SPA loads every bundle with Subresource Integrity, so the server pins each bundle's hash:

php artisan wave:web-pin           # record SHA-256 + version for every declared bundle
php artisan wave:web-pin --check   # exit 1 if any bundle on disk differs from its pin (deploy gate)
  • After sign-in the SPA fetches GET /_wave/api/v1/web-extensions?locale=pl|en. It lists every enabled plugin's declarative actions and, for a pinned bundle, its URL (/_wave/web-extensions/<author.plugin>/<version>/main.js, served with an immutable cache header) and integrity. The SPA inserts the script with that integrity and crossorigin="anonymous".
  • Run php artisan wave:web-pin and then --check on every deploy that ships a new or rebuilt bundle. winter:up does not pin (Winter boots no plugins while it runs), and an unpinned bundle is silently not loaded.
  • A bundle file that changes on disk without a re-pin fails SRI and does not run. Its bundle-dependent items stay hidden; declarative actions that don't need it still work.
  • A declared bundle that was never pinned is left out of the list (fail-closed), and a warning is logged.
  • The version in the bundle URL changes whenever the bytes change, so browsers never use a stale cached copy.
  • Deploy the backend (winter:up, then wave:web-pin) before the SPA, then check with wave:web-pin --check.

Dev loop

In development you can point the SPA at your plugin's own Vite dev server, with hot module reload. This works only in the SPA dev server: production builds drop the override code completely.

  1. Run npm run dev in your plugin's webapp/ (for example on port 5174).

  2. Tell the SPA where your plugin lives. Use either an env var in vue-wavepath-app/.env.local:

    VITE_PLUGIN_DEV_URLS='{"Author.Plugin":"http://localhost:5174/src/main.ts"}'
    

    or the same JSON in localStorage['wavepath-plugin-dev'] from the browser console:

    localStorage.setItem('wavepath-plugin-dev', JSON.stringify({ 'Author.Plugin': 'http://localhost:5174/src/main.ts' }))
    

    The localStorage value wins over the env var. Only localhost / 127.0.0.1 URLs are accepted.

The override is loaded as an ES module, without SRI. On serve, defineWavePathPlugin adds hostExternalsDev(), which maps vue, pinia and @wavepath/plugin-sdk to the host page's window.WavePath.*, so your dev server never serves a second Vue. In dev the host also accepts re-registration of the same id: a reload replaces your contributions.


Failure behaviour

A plugin can never break the app:

  • Bundles never block first paint. They load after sign-in, after the app is already on screen, all in parallel, each with a 10 s timeout.
  • Bad registrations are rolled back. If registerPlugin or initialize throws, or apiVersion is out of range, everything that plugin registered is removed.
  • Rendering errors are contained. Every slot render sits in an error boundary that renders nothing on error. The same protection covers predicates, handlers and click callbacks: a throw counts as "hidden" or "no-op".
  • Errors are logged, never shown. They go to the browser console, and to POST /_wave/api/v1/web-extensions/errors ({plugin, phase, message, stack?, version?}), which is rate-limited and writes to the Laravel log only. There is no admin page. The phases are ERROR_PHASES.
  • Users never see a plugin error. At worst, a plugin's items simply do not appear.

Worked example

The WavePath.XCapture plugin (plugins/wavepath/xcapture) shows the whole model:

  • a declarative "Capture from X" action, with a submenu of modes on desktop and flat rows on mobile;
  • a declarative destructive "Remove capture" item, with a confirm step;
  • a predicate-only bundle (webapp/) that registers the strict X-link predicates the rule grammar cannot express.

Its README points back here.


Versioning

  • Install the SDK by git tag: git+https://git.golem15.com/jakub/wavepath-plugin-sdk.git#v1.2.0. Your package-lock.json records the exact commit.
  • Releases within apiVersion 1 are additive. 1.1.0 added the theme tokens for light themes; 1.2.0 adds useConfig(), useShell(), the Popover kit, the back-dismissing Sheet and the inlineMedia / config declaration keys; 1.3.0 adds registerChannelWidget(); 1.4.0 adds registerSettingsSection() and exposes Input and Switch on host.components. apiVersion stays 1, so a plugin built against an earlier 1.x SDK runs unchanged on a 1.4.0 host.
  • The API version is the apiVersion of your PluginDefinition (PLUGIN_API_VERSION, currently 1). A breaking change to the contract bumps it, and the host keeps a compatibility range.
  • The host checks its runtime keys (window.WavePath.sdk, the registry methods, the built-in icons and the theme tokens) against contract.mjs and theme.css in this package. If they drift, the host's contract tests fail.
  • HOST_ICON_NAMES only ever grows.
Description
WavePath plugin SDK: registerPlugin types, Vite helper, Tailwind preset, author guide
Readme 278 KiB
Languages
JavaScript 70.3%
CSS 14.9%
TypeScript 14.8%