@opengeoweb/plugin-interface
v1.15.0
Published
A TypeScript library for GeoWeb plugin management, built with React, TypeScript, and Vite.
Maintainers
Keywords
Readme
Plugin Interface
A TypeScript library for GeoWeb plugin management, built with React, TypeScript, and Vite.
Automatic Releases
Releases are automatically created when code is merged to main using semantic-release. Use conventional commit messages to trigger version bumps.
Commit Types
| Commit Type | Version Bump | Example |
| ----------- | ------------ | ----------------------------- |
| fix: | Patch | fix: resolve memory leak |
| feat: | Minor | feat: add plugin validation |
| feat!: | Major | feat!: refactor plugin API |
Other types (docs:, test:, chore:, etc.) do not trigger releases.
Version Examples
| Current | Commit Type | New Version |
| ------- | ----------- | ----------- |
| 0.0.1 | fix: | 0.0.2 |
| 0.0.1 | feat: | 0.1.0 |
| 0.1.0 | feat!: | 1.0.0 |
Process
- Commit with conventional message (
fix:,feat:, etc.) - Merge to
mainbranch - CI/CD runs tests → builds → publishes (if tests pass)
Note: Only commits on main trigger releases. Multiple commits use the highest version bump type.
Plugin Generator
Generate a new plugin project from a template using an interactive prompt system or command-line arguments.
Quick Start
Using npx (recommended - no installation needed):
npx @opengeoweb/plugin-interfaceOr install globally:
npm install -g @opengeoweb/plugin-interface
create-pluginInteractive Mode (Recommended)
When you run create-plugin without arguments, you'll be prompted for all options:
npx @opengeoweb/plugin-interfaceThe interactive prompts will ask for:
- Plugin name: Name of your plugin (e.g.,
MyAwesomePlugin) - Scopes: Multi-select interface to choose from available scopes:
time- Time state management (setTime events)animation- Animation time span management (start/end times)features- Map features management (addLayer, removeLayer, setLayerFeatures)featureSelection- Selected feature ids within feature layers (setSelectedFeatures)applicationConfiguration- Read-only GeoWeb application configuration (host-pushed)notification- Send notifications with different severities to GeoWebuser- Read-only user authentication and profile information (host-pushed)authentication- Read-only authentication tokens and credentials (host-pushed)runtime- Runtime state of the plugin in the host, e.g. visibility (setPluginVisibility)mapLayers- Map layers of all host maps, set their httpOptions (setLayerHttpOptions)
- Plugin type:
view(renders a panel) oroverlay(renders on top of a view) - Close behavior (overlay only): what happens when the user closes the plugin window
disable- unregister and dispose the plugin (default)hide- keep the plugin running and only hide the window, e.g. so features stay on the map
- Initial version: Defaults to
1.0.0 - Output directory: Defaults to current directory
- Package name: Optional, defaults to
@your-org/<kebab-name>
Non-Interactive Mode
You can also provide all options via command-line arguments:
npx @opengeoweb/plugin-interface MyPlugin \
--scopes time,animation \
--version 1.0.0 \
--output-dir ./ \
--package-name @myorg/my-pluginCommand-Line Options
<plugin-name>(required in non-interactive mode): Name of your plugin--scopes <scope1,scope2>: Comma-separated list of scopes (default:time)--type <view|overlay>: Plugin type (default:view)--close-behavior <disable|hide>: Overlay plugins only; what happens when the plugin window is closed (default:disable)--version <version>: Initial version (default:1.0.0)--output-dir <dir>: Output directory (default: current directory)--package-name <name>: Package name (default:@your-org/<kebab-name>)--no-ci: Skip the GitLab release pipeline (.gitlab-ci.yml,.releaserc.json)--no-install: Skipnpm install(nopackage-lock.jsonwill be generated)
What Gets Generated
The generator creates a complete plugin project with:
- ✅ React component structure with scope integration
- ✅ TypeScript configuration
- ✅ Vite build configs
- ✅ Storybook setup for development and testing
- ✅ Default scope functionality (state subscriptions, event handlers, controls)
- ✅ Interactive demo story with scope controls
- ✅ Proper plugin interface integration
- ✅ Example event handlers and initialization code
- ✅ GitLab release pipeline with semantic-release (unless
--no-ci) - ✅ Installed dependencies and a
package-lock.json(unless--no-install)
Releasing a Generated Plugin
Generated plugins release through semantic-release. The branch you push to decides both the version and the target registry:
| Push to | Example version | Registry |
| --------- | --------------- | ------------------------------ |
| dev | 1.2.0-dev.1 | $PLUGIN_REGISTRY_URL_DEV |
| staging | 1.2.0-rc.1 | $PLUGIN_REGISTRY_URL_STAGING |
| main | 1.2.0 | $PLUGIN_REGISTRY_URL |
The version bump comes from conventional commit messages. The job authenticates
with a GitLab id_token minted per run and sent to the registry as basic auth,
so a generated project holds no registry credential at all — the only secret it
needs is GITLAB_TOKEN, which semantic-release uses to push tags. The
generated README's Releasing section is the reference: it lists the CI/CD
variables and where each value comes from, the GitLab setup the pipeline depends
on, and a table mapping each error string to its cause.
Example Usage
Interactive mode:
npx @opengeoweb/plugin-interface
# Follow the promptsNon-interactive mode:
npx @opengeoweb/plugin-interface WeatherWidget \
--scopes time,animation \
--version 0.1.0After generation:
cd weather-widget
npm install
npm run storybook # Start development server
npm run build:vite # Build for productionAvailable Scopes
time: Manages time state withsetTimeeventsanimation: Manages animation time spans withsetAnimationStartTime,setAnimationEndTime, andsetAnimationTimeSpaneventsfeatures: Manages map feature layers (GeoJSONFeatureCollections with optional styling) withaddLayer,removeLayer, andsetLayerFeatureseventsfeatureSelection: Manages the selected feature ids within feature layers withsetSelectedFeaturesevents. The state shape is{ featureLayers: { id, selectedFeatureIds }[] }.applicationConfiguration: Read-only view of the GeoWeb runtime configuration (filtered, host-pushed). Plugins subscribe viaonStateChange('applicationConfiguration', …)and cannot send events for this scope — the type system preventssendEvent('applicationConfiguration', …). The host updates the value withpluginManager.setScopeState('applicationConfiguration', { geowebConfig: … }).notification: Sends notifications to the GeoWeb host withshowNotificationevents. The host receives them viaPluginManager.subscribeToState('notification', ...), where each event becomes the scope state.user: Read-only user authentication and profile information (host-pushed). Plugins subscribe viaonStateChange('user', …)to access login state, user profile, and connection status. The host updates this viapluginManager.setScopeState('user', …).authentication: Read-only authentication tokens and low-level credentials (host-pushed). Plugins subscribe viaonStateChange('authentication', …)to access token details for authorization decisions. The host updates this viapluginManager.setScopeState('authentication', …).runtime: Runtime state of the plugin inside the host. Currently holdspluginVisibility('visible'or'hidden', default'visible'), which the plugin or the host changes withsetPluginVisibilityevents.mapLayers: The layers (wms,wmts,edrFeatures,stacorxyz) of all maps of the host, including base and over layers, each with itsmapIdand service and layer titles, filled by the host withsetScopeState('mapLayers', …). The state shape is{ layers: MapLayer[] }. A plugin sets the optionalhttpOptions(queryParams,requestHeaders) of a layer withsetLayerHttpOptionsevents.featureHover: Manages the currently hovered feature within a feature layer withsetHoveredFeaturesevents. The state shape is{ featureLayers: { id, hoveredFeatureIds }[] }. Currently only a single hovered feature per layer is supported; multi-hover may be added later. Layers with an emptyhoveredFeatureIdsarray are automatically pruned from state.
The generated plugin includes example code for all selected scopes, including state subscriptions, event handlers, and UI controls for testing.
Developing the Generator
If you're making changes to the generator templates or code, you need to rebuild the generator before testing:
Workflow
Make changes to templates in
templates/plugin-template/or generator code insrc/generator/Build the generator to compile your changes:
npm run buildRun the generator locally (relative path works):
node bin/create-plugin.jsTest the generated plugin:
cd [new-plugin-folder] npm install npm run storybook # Start Storybook to test your plugin
Testing local plugin-interface changes in a generated plugin
When you generate a plugin via node bin/create-plugin.js and want it to use your local plugin-interface code (instead of the published npm version), point its dependency to the local folder before installing:
In the generated plugin's
package.json, change the dependency to:"@opengeoweb/plugin-interface": "file:.."(Adjust the path if your plugin lives somewhere else.)
From the
plugin-interfacerepo root, build the library so the localdist/is up to date:npm run buildThen in the generated plugin folder:
npm install npm run storybook
Whenever you change plugin-interface, rerun npm run build in the root; the generated plugin will pick up the updated local build.
Quick Reference
# After making template changes
npm run build
# Generate a new plugin
node bin/create-plugin.js
# Test the generated plugin
cd [new-plugin-folder]
npm install
npm run storybookDevelopment
npm install # Install dependencies
npm run dev # Development server
npm test # Run tests
npm run build # Build library
npm run lint # Lint codeHow npm run build works
npm run build runs:
| Tool | Output | Consumer |
| ------------------------- | -------------------------- | ---------------------------------------------------------- |
| tsdown | dist/index.{js,cjs,d.ts} | Generated plugins importing @opengeoweb/plugin-interface |
| tsc (build:generator) | dist/generator/*.js | The create-plugin CLI in bin/create-plugin.js |
tsdown's handling of package.json:
peerDependenciesleft external.dependenciesleft external.devDependencies— bundled intodist/(if anything in the runtime code path imports them).
Local Development with OpenGeoWeb
To test changes to the plugin-interface library directly inside OpenGeoWeb, you can use npm link for local development.
Why use npm link?
When developing plugins or working on the plugin-interface, you often need to:
- Test changes in a real OpenGeoWeb environment
- Iterate quickly on plugin behavior and APIs
- Avoid publishing a new package version for every small change
npm link allows you to use your local version of plugin-interface inside OpenGeoWeb, so you can immediately see the effect of your changes while developing plugins.
This makes it much faster to develop, debug, and validate plugin integrations.
Steps
Make changes in the
plugin-interfacerepositoryBuild the library:
npm run buildLink the package globally:
npm linkOpen the OpenGeoWeb project and link the package:
npm link @opengeoweb/plugin-interfaceStart OpenGeoWeb:
nx serveYou should now see your local changes reflected in OpenGeoWeb.
Updating Changes
- After making new changes in
plugin-interface, rebuild:npm run build
No need to relink, OpenGeoWeb will pick up the updated build automatically.
Storybook
Storybook provides an interactive development environment for exploring and testing plugin integrations in isolation.
Running Storybook
npm run dev # Start Storybook dev server (usually http://localhost:6006)Available Stories
Located in the ./dev folder:
- PluginIntegration: Shows real-time interaction with plugin state (time, animation, lifecycle controls)
Benefits
- Isolated Development: Test components without running the full application
- Live Documentation: Interactive examples with editable props via Controls panel
- Visual Testing: See component states and variations side-by-side
- Accessibility: Built-in a11y addon helps catch accessibility issues early
- Rapid Prototyping: Quickly iterate on plugin behavior and UI integration
Stories include comprehensive documentation explaining the plugin architecture, custom hooks, and usage patterns.
Observing Plugin Events (subscribeToEvent)
PluginManager.subscribeToEvent(scope, callback) lets the host application
observe plugin-originated events for a given scope. It is complementary to
subscribeToState:
subscribeToState(scope, cb)— fires whenever the scope's state changes (from either the host or a plugin). Use this to render the current state.subscribeToEvent(scope, cb)— fires only when a plugin dispatches an event for the scope.
Example
import { PluginManager } from 'plugin-interface';
const manager = new PluginManager();
const unsubscribe = manager.subscribeToEvent('features', (event) => {
switch (event.type) {
case 'addLayer':
console.log('Plugin added a layer:', event.layer);
break;
case 'removeLayer':
console.log('Plugin removed layer:', event.layerId);
break;
case 'setLayerFeatures':
console.log(
`Plugin updated features for ${event.layerId}:`,
event.featureCollection,
);
break;
}
});
// Later, when no longer interested:
unsubscribe();The callback is fully typed against ScopeEventMap[scope], so the event
union is narrowed per-scope.
Time Scope API
import {
PluginManager,
setTime,
toIso8601Utc,
assertIso8601Utc,
type Iso8601Utc,
} from 'plugin-interface';
const manager = new PluginManager();
const instance =
/* previously registered plugin instance with 'time' scope */ null as any;
// Basic: pass a valid UTC timestamp literal (compile-time shape checked)
setTime(instance, '2024-10-10T10:10:10Z');
// From Date: convert explicitly
const isoFromDate = toIso8601Utc(new Date());
setTime(instance, isoFromDate);
// Dynamic strings: setTime performs runtime validation and throws on invalid input
const raw = await fetchSomeTimestamp();
setTime(instance, raw);
// Optional pre-validation for clearer local error handling
try {
const safe: Iso8601Utc = assertIso8601Utc(raw);
setTime(instance, safe);
} catch (err) {
console.error('Invalid time format', err);
}
// Explicit conversion example
const iso: Iso8601Utc = toIso8601Utc(new Date('2025-01-01T00:00:00.999Z'));
setTime(instance, iso);Time Format & Validation
- Format: UTC ISO 8601 at seconds precision (
YYYY-MM-DDTHH:MM:SSZ). - Compile-time: template literal type
Iso8601Utcvalidates only literal shapes. - Runtime:
setTimeand helpers validate strings; errors include actionable hints (e.g., milliseconds present).
Helpers
setTime(instance, iso): Dispatches thetimescopesetTimeevent ifisois valid.toIso8601Utc(date): Returns a compliant UTC string; removes milliseconds.assertIso8601Utc(str): Throws ifstris not compliant; narrows type toIso8601Utcwhen valid.
If you need offsets or milliseconds support in the future, extend the validation and helpers while preserving the current API surface.
Application Configuration Scope API
The applicationConfiguration scope exposes a filtered, read-only view of the host's runtime configuration (config.json) to plugins.
import {
PluginManager,
type ApplicationConfig,
type ApplicationConfigurationState,
} from '@opengeoweb/plugin-interface';
// In the host app (GeoWeb): push the redacted config into the manager.
const filtered: ApplicationConfig = {
frontend: {
global: {
sentryEnabled: true,
initialPresetsFilename: 'default',
},
},
backend: {
trajks: {
baseUrl: 'https://api.geoweb.example/v1',
workspaceId: '123456789',
},
warnings: {
baseUrl: 'https://warnings.geoweb.example/api',
},
},
};
manager.setScopeState('applicationConfiguration', { geowebConfig: filtered });
// In a plugin: subscribe to the read-only state.
instance.onStateChange(
'applicationConfiguration',
(state: ApplicationConfigurationState) => {
console.log(state.geowebConfig.backend.trajks.baseUrl);
},
);Notification Scope API
The notification scope lets a plugin push notifications (snackbars, banners, toasts) to the GeoWeb host. GeoWeb decides how to present them.
A plugin emits a notification with sendEvent:
import type { GeoWebPluginInstance } from '@opengeoweb/plugin-interface';
declare const instance: GeoWebPluginInstance;
instance.sendEvent('notification', {
type: 'showNotification',
severity: 'SUCCESS',
content: 'Form published',
});The host receives notifications through the standard scope subscription. The notification state starts as {} and is replaced by the event itself when one fires, so the state shape matches NotificationScopeEvent:
const unsubscribe = manager.subscribeToState('notification', (state) => {
if (state.type) {
showSnackbar(state.severity, state.content);
}
});The if (state.type) guard skips the initial empty replay before any notification has fired.
User Scope API
The user scope exposes read-only authentication and profile information to plugins.
import { PluginManager, type UserState } from '@opengeoweb/plugin-interface';
// In the host app (GeoWeb): push the user state into the manager.
const userState: UserState = {
isLoggedIn: true,
user: {
username: 'john.doe',
firstName: 'John',
lastName: 'Doe',
rolesPerIssuer: [
{
issuer: 'geoweb',
roles: ['admin', 'editor'],
},
],
},
hasConnectionIssue: false,
};
manager.setScopeState('user', userState);
// In a plugin: subscribe to the read-only state.
instance.onStateChange('user', (state: UserState) => {
if (state.isLoggedIn) {
console.log(`Welcome, ${state.user?.firstName}`);
} else {
console.log('User not logged in');
}
});Authentication Scope API
The authentication scope exposes low-level token details and credentials to plugins for fine-grained authorization decisions.
import {
PluginManager,
type AuthenticationState,
} from '@opengeoweb/plugin-interface';
// In the host app (GeoWeb): push the authentication state into the manager.
const authState: AuthenticationState = {
tokens: [
{
issuer: 'geoweb-auth',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
refreshToken: 'refresh_token_123',
roles: ['admin', 'trajks:publish_form'],
tokenExpiresAt: Date.now() + 3600000,
},
],
};
manager.setScopeState('authentication', authState);
// In a plugin: subscribe to access token details.
instance.onStateChange('authentication', (state: AuthenticationState) => {
const canPublishForm = state.tokens.some((token) =>
token.roles.includes('trajks:publish_form'),
);
console.log('Can publish:', canPublishForm);
});Both user and authentication are read-only from the plugin's perspective. Plugins cannot send events for these scopes; the host manages them via setScopeState.
Runtime Scope API
The runtime scope holds the plugin's own state inside the host. The host creates one PluginManager per plugin, so the values describe that plugin only. Both sides can change it.
| Field | Values | Default | Event |
| ------------------ | ----------------------- | ----------- | --------------------- |
| pluginVisibility | 'visible', 'hidden' | 'visible' | setPluginVisibility |
hidden means the plugin is still registered but not shown, for example an overlay closed with closeBehavior: 'hide'.
import type { RuntimeState } from '@opengeoweb/plugin-interface';
// In a plugin: hide or show itself.
instance.sendEvent('runtime', {
type: 'setPluginVisibility',
pluginVisibility: 'hidden',
});
// In a plugin: pause work while hidden, whoever hid it.
instance.onStateChange('runtime', (state: RuntimeState) => {
if (state.pluginVisibility === 'hidden') {
stopPolling();
} else {
startPolling();
}
});
// In the host app (GeoWeb): let the window follow the state. This fires for
// changes from the plugin and from the host.
manager.subscribeToState('runtime', (state) => {
setWindowOpen(state.pluginVisibility === 'visible');
});
// In the host app: tell the plugin when the user hides or shows the window.
manager.sendEvent('runtime', {
type: 'setPluginVisibility',
pluginVisibility: 'hidden',
});Events change only the field they name. setScopeState('runtime', …) replaces the whole state, so once the scope holds more fields the host should prefer events.
Map Layers Scope API
The mapLayers scope shows the plugin the layers of all maps of the host, including base and over layers (maps in host order, top layer first within each map), and lets it set extra HTTP options (httpOptions) for them. The state is MapLayersState: { layers: MapLayer[] }. Every layer has the same generic properties: id, mapId (the host map the layer is on), type ('wms' | 'wmts' | 'edrFeatures' | 'stac' | 'xyz'), optional serviceTitle and layerTitle (the titles as the host shows them to the user; layerTitle may be a fallback such as the layer name), visible (boolean), opacity and optional httpOptions. Everything that is specific to the layer type, such as the service URL and the layer name, is in options, so it never mixes with the generic properties. The shape of options depends on type:
| type | options type | Fields |
| ------------- | --------------------------------- | ------------------------------------------- |
| wms | MapLayerWMSLayerOptions | url, name, optional style |
| wmts | MapLayerWMTSLayerOptions | url, name, optional style |
| edrFeatures | MapLayerEDRFeaturesLayerOptions | url, collectionId, parameterNames |
| stac | MapLayerSTACLayerOptions | url, optional name, optional assetKey |
| xyz | MapLayerXYZLayerOptions | name (tile set in the host, no URL) |
Check type first: TypeScript then narrows options to the matching type. visible, opacity and options are read-only: only the host changes them. A plugin changes the requests of a layer through httpOptions.
httpOptions has two optional fields: queryParams (extra query parameters for the data requests of the layer, e.g. WMS GetMap and GetLegendGraphic, WMTS and XYZ tiles, EDR and STAC requests; don't use them for standard parameters like LAYERS, STYLES or TIME) and requestHeaders (extra request headers). A host may not support every option, so check the state to see what the host applied.
import type { MapLayersState } from '@opengeoweb/plugin-interface';
// In a plugin: read the layers and set httpOptions on one of them.
instance.onStateChange('mapLayers', (state: MapLayersState) => {
const layer = state.layers.find(
(l) => l.type === 'wms' && l.options.name === 'precipitation',
);
// The plugin also receives the state change from its own event, so only
// send when the layer does not have the option yet.
if (layer && layer.httpOptions?.queryParams?.DIM_MODEL !== 'harmonie') {
instance.sendEvent('mapLayers', {
type: 'setLayerHttpOptions',
layerId: layer.id,
httpOptions: { queryParams: { DIM_MODEL: 'harmonie' } },
});
}
});
// In a plugin: remove the httpOptions again (`undefined`, `{}` or only empty fields).
instance.sendEvent('mapLayers', {
type: 'setLayerHttpOptions',
layerId: 'layer-1',
httpOptions: undefined,
});
// In the host app (GeoWeb): publish the layers of all maps.
manager.setScopeState('mapLayers', {
layers: [
{
id: 'layer-1',
mapId: 'map-1',
type: 'wms',
serviceTitle: 'Example WMS',
layerTitle: 'Precipitation',
visible: true,
opacity: 1,
options: {
url: 'https://wms.example/wms',
name: 'precipitation',
},
},
],
});
// In the host app: apply the httpOptions to the layer on the map.
manager.subscribeToEvent('mapLayers', (event) => {
setLayerHttpOptions(event.layerId, event.httpOptions);
});The host only handles setLayerHttpOptions for layers it published. Events for unknown layer ids leave the state unchanged. The event replaces the httpOptions of the layer as a whole.
Feature Hover Scope API
The featureHover scope tracks which feature is currently hovered within a feature layer. Plugins dispatch setHoveredFeatures events; the host receives them via subscribeToState or subscribeToEvent.
Note: Currently only a single hovered feature per layer is supported. Pass exactly one ID in
hoveredFeatureIds. Multi-hover may be added in a future release.
import type { GeoWebPluginInstance } from '@opengeoweb/plugin-interface';
declare const instance: GeoWebPluginInstance;
// Set the hovered feature for a layer
instance.sendEvent('featureHover', {
type: 'setHoveredFeatures',
featureLayerId: 'weather-layer',
hoveredFeatureIds: ['feature-1'],
});
// Clear hover for a layer (empty array removes the layer from state)
instance.sendEvent('featureHover', {
type: 'setHoveredFeatures',
featureLayerId: 'weather-layer',
hoveredFeatureIds: [],
});The host subscribes to hover changes:
import {
PluginManager,
type FeatureHoverState,
} from '@opengeoweb/plugin-interface';
const manager = new PluginManager();
const unsubscribe = manager.subscribeToState(
'featureHover',
(state: FeatureHoverState) => {
for (const layer of state.featureLayers) {
console.log(
`Layer ${layer.id} hovered feature:`,
layer.hoveredFeatureIds[0],
);
}
},
);State details:
state.featureLayersonly contains layers with an active hover — layers are pruned automatically whenhoveredFeatureIdsis set to[].- Dispatching
setHoveredFeaturesfor an unknown layer ID appends a new entry; for an existing layer it replaceshoveredFeatureIdsin place.
