@automationview/api
v4.2.0
Published
Public API types and utilities for AutomationView extension plugins
Maintainers
Readme
@automationview/api
Public API for building AutomationView plugins.
This package provides the types, base classes, builders and utilities needed to create export, import and translation providers that convert Sequence/SFC projects into PLC-compatible formats (PLCopen XML, Structured Text, CSV, etc.), to contribute custom actions and data types, and to register equipment catalogs (manufacturers, devices, development software).
Installation
npm install @automationview/apiQuick Start
1. Write an export provider
Extend AbstractExportProvider: the base class handles duration tracking,
progress, cancellation and error-to-diagnostic conversion. You only implement
doExport.
import { AbstractExportProvider, DiagnosticBuilder } from '@automationview/api';
import type {
ProjectExportData, ExportOptions, ExportResult,
ExportProgress, APICancellationToken,
} from '@automationview/api';
class MyProvider extends AbstractExportProvider {
constructor() {
super({
id: 'my-provider',
devSoftwareId: 'codesys-v3',
supportedFormats: [{
format: 'plcopen-xml',
displayName: 'PLCopen XML',
fileExtension: '.xml',
}],
});
}
async doExport(
data: ProjectExportData,
options: ExportOptions,
progress?: (info: ExportProgress) => void,
token?: APICancellationToken,
): Promise<ExportResult> {
const diagnostics = [
DiagnosticBuilder.info('START', 'Export started').build(),
];
this.reportProgress(progress, 'Starting export...', 0);
for (const sequence of data.sequences) {
this.checkCancellation(token);
// process each sequence...
}
this.reportProgress(progress, 'Done', 100);
return {
success: true,
outputs: [],
outputFiles: [],
diagnostics,
durationMs: 0,
format: options.format,
};
}
}ExportResult.outputs carries the artifacts ({ path, content }); the host
writes them with its own file system. outputFiles is the list of paths those
outputs land on.
For a structured generator, extend BaseExportProvider<TAdapter> instead - it
is what the official plugins use. It drives a fixed pipeline (variables,
POUs, steps, transitions, main program, serialize), classifies variables,
orders sequences, reports progress and checks cancellation between phases; you
fill in the hooks:
import { BaseExportProvider, TextFormatAdapter, ExportContext } from '@automationview/api';
import type {
POUExportData, SequenceData, StepData, TransitionData,
VariableData, VariableGroup,
} from '@automationview/api';
class MySTProvider extends BaseExportProvider<TextFormatAdapter> {
constructor() {
super({
id: 'my-st-export',
devSoftwareId: 'codesys-v3',
supportedFormats: [{
format: 'iec-st',
displayName: 'IEC Structured Text',
fileExtension: '.st',
}],
});
}
protected createAdapter(): TextFormatAdapter {
return new TextFormatAdapter();
}
protected onInitialize(_ctx: ExportContext, adapter: TextFormatAdapter): void {
adapter.writeLine('(* Generated by AutomationView *)');
}
protected onProjectHeader(ctx: ExportContext, adapter: TextFormatAdapter): void {
adapter.writeLine(`(* Project: ${ctx.data.machine.name} *)`);
}
protected onVariable(
variable: VariableData,
_group: VariableGroup,
_ctx: ExportContext,
adapter: TextFormatAdapter,
): void {
adapter.writeLine(` ${variable.name} : ${variable.dataType};`);
}
protected onBeginPOU(pou: POUExportData, _ctx: ExportContext, adapter: TextFormatAdapter): void {
adapter.writeLine(`PROGRAM ${pou.name}`);
}
protected onEndPOU(_pou: POUExportData, _ctx: ExportContext, adapter: TextFormatAdapter): void {
adapter.writeLine('END_PROGRAM');
}
protected onStep(
step: StepData,
_sequence: SequenceData,
_ctx: ExportContext,
adapter: TextFormatAdapter,
): void {
adapter.writeLine(` (* step ${step.name} *)`);
}
protected onTransition(
transition: TransitionData,
_sequence: SequenceData,
_ctx: ExportContext,
adapter: TextFormatAdapter,
): void {
adapter.writeLine(` (* transition ${transition.id} *)`);
}
protected onSerialize(_ctx: ExportContext, adapter: TextFormatAdapter): string {
return adapter.serialize();
}
}2. Register the provider
Use getAutomationViewAPI() to obtain the API:
import * as vscode from 'vscode';
import { getAutomationViewAPI } from '@automationview/api';
export async function activate(context: vscode.ExtensionContext): Promise<void> {
const api = await getAutomationViewAPI();
if (!api) return;
const disposable = api.registerExportProvider(new MyProvider());
context.subscriptions.push(disposable);
}Equipment Registration
Equipment registration follows a dependency chain: manufacturer -> equipment -> development software. All three must be registered for the equipment catalog to be complete.
Using EquipmentBuilder (recommended)
EquipmentBuilder provides a fluent API with a callback pattern for building
deeply nested equipment objects:
import {
createManufacturer,
createDevSoftware,
getAutomationViewAPI,
EquipmentBuilder,
} from '@automationview/api';
// 1. Create manufacturer
const siemens = createManufacturer({
id: 'siemens',
displayName: 'Siemens',
country: 'Germany',
website: 'https://siemens.com',
});
// 2. Build equipment with versions, channels, and parameters
const s71200 = EquipmentBuilder
.create('s7-1200', 'siemens', 'S7-1200', 'controller', 'profinet')
.description('Compact controller for small to medium applications')
.partNumbers(['6ES7214-1AG40-0XB0'])
.addVersion('V4.5', v => v
.partNumber('6ES7214-1AG40-0XB0')
.addChannel('DI0', 'Digital Input 0', 'input', 'BOOL', 0, 1)
.addChannel('DI1', 'Digital Input 1', 'input', 'BOOL', 0, 1, { bitOffset: 1 })
.addChannel('DQ0', 'Digital Output 0', 'output', 'BOOL', 2, 1)
.addParameter('cycle-time', 'CYCLE_TIME', 'Cycle Time', 'INT', 10, { unit: 'ms', min: 1, max: 1000 })
)
.build();
// 3. Create development software
const tiaPortal = createDevSoftware({
id: 'tia-portal-v18',
displayName: 'TIA Portal V18',
vendor: 'Siemens',
plcopenXmlSupport: 'partial',
supportedEquipmentIds: ['s7-1200'],
});
// 4. Register with the API
const api = await getAutomationViewAPI();
if (api) {
context.subscriptions.push(
api.registerManufacturer(siemens),
api.registerEquipment(s71200),
api.registerDevSoftware(tiaPortal),
);
}The callback passed to EquipmentBuilder.addVersion receives a version builder
carrying partNumber, addChannel, addParameter (plus addChannelObject
and addParameterObject for pre-built objects). That builder type is not
exported: take it from the callback rather than importing it.
Using factory functions
For simpler cases, use the individual factory functions:
import {
createEquipmentVersion,
createIOChannel,
createEquipmentParameter,
} from '@automationview/api';
const channel = createIOChannel({
id: 'AI0',
name: 'Analog Input 0',
direction: 'input',
dataType: 'INT',
addressOffset: 0,
bitSize: 16,
unit: 'mA',
range: { min: 0, max: 20 },
});
const param = createEquipmentParameter({
id: 'filter-time',
name: 'FILTER_TIME',
displayName: 'Filter Time',
dataType: 'INT',
defaultValue: 50,
unit: 'ms',
});
const version = createEquipmentVersion({
version: 'V1.0',
channels: [channel],
parameters: [param],
});Arrays
Array-ness is a modifier on the element type, never a type of its own.
dataType keeps naming the ELEMENT type and arrayBounds?: ArrayBounds[]
carries the declared dimensions, exactly the way stringLength already sits
beside STRING. VariableData, VariableDeclaration, CustomTypeField and
the type-registry child definitions all follow this shape.
Your type map therefore keeps matching on the bare element type, and you only wrap your target's own array syntax around it:
import type { VariableData } from '@automationview/api';
function declare(v: VariableData): string {
const elem = TYPE_MAP[v.dataType];
if (!v.arrayBounds?.length) return `${v.name} : ${elem};`;
const dims = v.arrayBounds.map(b => `${b.lo}..${b.hi}`).join(', ');
return `${v.name} : ARRAY[${dims}] OF ${elem};`;
}Bounds are stored exactly as the author wrote them - multi-dimensional, and
free to start anywhere, including at a negative lower bound. The host never
normalizes them. If your target only accepts 0-based arrays, rebase at export
(0..(hi - lo)) and emit a warning-severity diagnostic naming the original
bounds; do not rewrite the user's declaration.
Limits and helpers: MAX_ARRAY_DIMENSIONS (6), MAX_ARRAY_ELEMENTS (65536),
isValidArrayBounds(bounds) and arrayElementCount(bounds).
Variable paths
Parsing and resolving axes[i].position is public API - a provider that
reimplements it will disagree with the host's diagnostics.
| Export | Description |
|--------|-------------|
| parseVariablePath(text) | Parse a path into a VariablePath, or undefined when the text is malformed |
| parseVariablePathDetailed(text) | Parse with a VariablePathParse result carrying VariablePathError detail |
| formatVariablePath(path) | Render a VariablePath back to text |
| collectPathVariableRefs(path) | Every variable name a path references, subscripts included |
| pathHasIndex(path) | Whether any segment is subscripted |
| resolveVariablePath(path, resolveSymbol, options?) | Walk a parsed path to what it addresses; returns PathResolution |
| describeVariablePathError(code, text) | Human-readable text for a parse error |
| isIndexDataType(dataType) | Whether a type is usable as a subscript |
Related types: VariablePath, PathSegment, PathIndex,
VariablePathParse, VariablePathError, VariablePathErrorCode,
SymbolShape, SymbolResolver, TypeLookup, ResolveOptions,
PathResolution, PathIssue, PathIssueCode.
Gotcha: pass ResolveOptions.types
This package bundles its copy of the shared code, so your plugin gets its
OWN TypeRegistry instance, not the host's. The default type lookup inside
resolveVariablePath consults that bundled registry: built-in compound pins
(TON.Q) resolve fine, but a field of a project-defined STRUCT, or an
ENUM used as a subscript, will not - and those are exactly what you are
emitting declarations for.
Build a TypeLookup from the machine data you were handed and pass it.
membersOf returns the members keyed by name, or undefined when the type has
none:
import { parseVariablePath, resolveVariablePath } from '@automationview/api';
import type { MachineData, TypeLookup } from '@automationview/api';
function typeLookup(machine: MachineData): TypeLookup {
return {
membersOf: name => {
const type = machine.customTypes?.find(t => t.name === name);
if (!type?.fields) return undefined;
return Object.fromEntries(type.fields.map(f => [
f.name,
{ dataType: f.dataType, arrayBounds: f.arrayBounds },
]));
},
isEnumType: name =>
machine.customTypes?.some(
t => t.name === name && t.category === 'ENUM',
) ?? false,
};
}
const path = parseVariablePath('axes[i].position');
if (path) {
const resolution = resolveVariablePath(
path,
resolveSymbol,
{ types: typeLookup(machine) },
);
// resolution.ok tells you whether the path addresses anything.
}parseVariablePath returns undefined on malformed text; use
parseVariablePathDetailed when you need the VariablePathError behind the
failure.
Roots, array bounds and index checks come from the SymbolResolver you supply
and never touch a registry, so only FIELD segments and ENUM subscripts need
this.
String and conversion instructions
3.0.0 adds fifteen IEC 61131-3 instructions as built-in actions:
| Category | Instructions |
|---|---|
| String | CONCAT, LEN, LEFT, RIGHT, MID, FIND, REPLACE, INSERT, DELETE |
| Conversion | INT_TO_STRING, DINT_TO_STRING, REAL_TO_STRING, STRING_TO_INT, STRING_TO_REAL, BOOL_TO_STRING |
List the ids your generator actually compiles in supportedInstructions.
An instruction no provider declares for a target reports unsupported there
and exports as an AUTOMATIONVIEW: unsupported action ... comment placeholder
plus a warning diagnostic. See also the helpers under
Action support.
Action parameter binding
Every entry of ActionDefinition.parameters[] says where its own value is
stored, through ActionParameterDescriptor.binding. There is no
definition-level binding: 4.0.0 removed ActionDefinition.parameterBinding
precisely so one action can mix storages.
| binding | Storage | Read back with |
|---|---|---|
| keyed (default) | ActionData.parameters[descriptor.id] | getParameter(id) |
| positional | ActionData.operands[k] | resolveOperand(ctx, k) |
| field | the dedicated ActionData field named by descriptor.id | the field's own accessor |
An absent binding means keyed, which is how every plugin parameter has
always been stored - so a plugin that declares nothing keeps working unchanged.
field is limited to the dedicated fields listed in
ACTION_FIELD_PARAMETER_IDS (duration, presetValue), which
isActionFieldParameterId checks. A field descriptor with any other id has
no storage behind it.
k counts positional descriptors only, never the index in parameters[].
A field or keyed descriptor declared in front of an operand slot is
transparent to the count and does not shift it:
import type { ActionParameterDescriptor } from '@automationview/api';
const parameters: ActionParameterDescriptor[] = [
// dedicated ActionData.duration - consumes no operand slot
{ id: 'duration', binding: 'field', label: 'PT', type: 'duration', dataType: 'TIME', required: true },
// parameters[1], but the FIRST positional descriptor, so operands[0]
{ id: 'R', binding: 'positional', label: 'R', type: 'variable', dataType: 'BOOL', required: false },
];That is exactly how the built-in RTO is declared, and it is what makes its
reset input land on the operand index RetentiveTimerAction actually reads.
See docs/migration-4.0.md for the full rationale and a helper you can copy.
Simulation models
A plugin can ship plant (digital twin) models for its module classes or
equipment: the emulator and av simulate run them before every scan, for the
classes and equipment a project's plant.yaml does not model, whenever a
plant is enabled. The rules are the plant.yaml primitives (follow,
bistable, ramp, pulse_train, counter); see the av simulate
documentation of the CLI for their behaviour.
registerSimulationModel is optional on the host API: hosts built against an
older @automationview/api do not have it, so call it with ?..
import { createSimulationModel, getAutomationViewAPI } from '@automationview/api';
const api = await getAutomationViewAPI();
const model = createSimulationModel({
id: 'acme.cylinder',
className: 'Cylinder',
rules: [
{
bistable: { extend: '{extend}', retract: '{retract}', travel: '300ms', at_end: '{is_extended}', at_start: '{is_retracted}' },
params: { bistable: true },
},
],
});
const registration = api?.registerSimulationModel?.(model);
registration?.dispose();createSimulationModel throws a TypeError listing every problem;
validateSimulationModel(model) returns them instead.
API Reference
Export Provider Framework
| Export | Description |
|--------|-------------|
| AbstractExportProvider | Base class with cancellation, progress, and error handling |
| BaseExportProvider | Template-method pipeline on top of AbstractExportProvider |
| BaseDiagnosticProvider | Base for validation-diagnostic providers |
| ExportContext | Context carried through one export run |
| CancellationError | Error thrown to signal a cancelled export |
| DiagnosticBuilder | Fluent builder for ExportDiagnostic objects |
| classifyVariables(variables) | Groups variables (inputs, outputs, timers, ...) |
| getVariablesByGroup(classified, group) | Reads one group out of a ClassifiedVariables |
| VARIABLE_GROUP_ORDER | Canonical group order |
Format adapters: TextFormatAdapter and XmlFormatAdapter, both implementing
the FormatAdapter contract.
DiagnosticBuilder
import { DiagnosticBuilder } from '@automationview/api';
const err = DiagnosticBuilder.error('MISSING_VAR', 'Variable "x" not declared')
.source('MyProvider')
.suggestion('Declare variable "x" before export')
.build();
const warn = DiagnosticBuilder.warning('LONG_NAME', 'Name exceeds 32 chars').build();
const info = DiagnosticBuilder.info('SKIPPED', 'Empty step skipped').build();Import and Translation Providers
| Export | Description |
|--------|-------------|
| AbstractImportProvider | Base class for importers |
| BaseTranslationProvider | Base class for translation providers |
Action support
| Export | Description |
|--------|-------------|
| rewriteSequenceForActionSupport(...) | Rewrites a sequence according to the support verdict |
| actionSupportDiagnostics(...) | Diagnostics for unsupported actions |
| splitUnsupportedActions(...) | Splits supported actions from the rest |
| unsupportedActionNote(...) | Placeholder comment text |
Equipment Builder & Factories
| Export | Description |
|--------|-------------|
| EquipmentBuilder | Fluent builder for EquipmentInfo with callback-based version nesting |
| createManufacturer(config) | Factory for ManufacturerInfo objects |
| createDevSoftware(config) | Factory for DevSoftwareInfo objects |
| createIOChannel(config) | Factory for IOChannel objects |
| createEquipmentVersion(config) | Factory for EquipmentVersion objects |
| createEquipmentParameter(config) | Factory for EquipmentParameter objects |
Custom actions and data types
| Export | Description |
|--------|-------------|
| createAction(config) | ActionDefinition factory (routed to the host runtime) |
| createActionCategory(config) | ActionCategoryDefinition factory |
| createTypeDefinition(config) | TypeDefinition factory |
| createChildDefinition(config) | Field or pin factory (arrayBounds aware) |
| TypeDefinitionBuilder | Fluent builder for nested types |
| AbstractAction, ActionState | Action base class and state, supplied by the host runtime |
| unwrapParameterValue(value) | Extracts the raw value out of an ActionParameterValue |
| DEFAULT_WIDGET_BY_TYPE | Default widget for each ParameterValueType |
| isSemanticId(id), SEMANTIC_ID_PATTERN | Semantic identifier validation |
| createSimulationModel(config) | Validated SimulationModel for registerSimulationModel (Simulation models) |
| validateSimulationModel(model), parseDurationMs(value) | Simulation model problems; duration texts (300ms, T#1s) to milliseconds |
VS Code helpers
| Export | Description |
|--------|-------------|
| getAutomationViewAPI() | Retrieves the AutomationView API. Returns Promise<IAutomationViewAPI \| undefined> |
Type Guards
| Export | Description |
|--------|-------------|
| isManufacturerInfo(obj) | Checks for ManufacturerInfo shape |
| isEquipmentInfo(obj) | Checks for EquipmentInfo shape |
| isDevSoftwareInfo(obj) | Checks for DevSoftwareInfo shape |
| isExportProviderDescriptor(obj) | Checks for IExportProviderDescriptor shape |
| isIOChannel(obj) | Checks for IOChannel shape |
| isEquipmentVersion(obj) | Checks for EquipmentVersion shape |
| isEquipmentParameter(obj) | Checks for EquipmentParameter shape |
| isNamingConvention(obj) | Checks for NamingConvention shape |
| isActionDefinition(obj) | Checks for ActionDefinition shape |
| isActionCategoryDefinition(obj) | Checks for ActionCategoryDefinition shape |
| isTypeDefinition(obj) | Checks for TypeDefinition shape |
| isChildDefinition(obj) | Checks for ChildDefinition shape |
Enums
| Export | Values |
|--------|--------|
| ActionInstruction | MOVE, SR, RS, R_TRIG, F_TRIG, ADD, SUB, MUL, DIV, TON, TOF, CONCAT, LEN, ... |
| ActionQualifier | N, S, R, L, D, P, SD, DS, SL |
| StepType | INITIAL, NORMAL, MACRO, ENCLOSING |
Re-exported Types
All types needed by plugins are available directly from
@automationview/api:
import type {
// Sequence data model
SequenceData, StepData, TransitionData, ActionData, ActionOperand,
// Variables and project
VariableData, VariableDataType, VariableDeclaration, MachineData,
CustomTypeDefinition, CustomTypeField, CustomEnumValue, Instance,
// Arrays and paths
ArrayBounds, VariablePath, PathSegment, PathIndex,
SymbolShape, SymbolResolver, TypeLookup, ResolveOptions, PathResolution,
// Equipment
ManufacturerInfo, EquipmentInfo, DevSoftwareInfo, NamingConvention,
EquipmentCategory, CommunicationProtocol, IOChannel, EquipmentVersion,
EquipmentParameter, EquipmentParameterDataType, ParameterValue,
// Export, import, translation
ExportOptions, ExportResult, ExportOutput, ExportDiagnostic, ProjectExportData,
POUExportData, MainProgramConfig, MainProgramCall,
ImportOptions, ImportResult, ImportDiagnostic, IImportProvider,
TranslationOptions, TranslationResult, ITranslationProvider,
// Actions and types
ActionDefinition, ActionCategoryDefinition, ActionParameterDescriptor,
ActionParameterBinding, ActionParameterValue, ActionFieldParameterId,
TypeDefinition, TypeCategory, ChildDefinition,
// API core
IAutomationViewAPI, IExportProviderDescriptor, APICancellationToken,
// Config types
ManufacturerConfig, DevSoftwareConfig, IOChannelConfig,
EquipmentVersionConfig, EquipmentParameterConfig,
} from '@automationview/api';Package Structure
src/
index.ts Barrel exports (grouped by category)
constants.ts Shared constants
actions/ Custom action contributions
createAction.ts ActionDefinition factory
createActionCategory.ts ActionCategory factory
datatypes/ Custom data type contributions
createTypeDefinition.ts TypeDefinition factory
createChildDefinition.ts Child/field factory (arrayBounds aware)
TypeDefinitionBuilder.ts Fluent builder for nested types
equipment/ Equipment builder & factories
EquipmentBuilder.ts Fluent builder for EquipmentInfo
createManufacturer.ts ManufacturerInfo factory
createDevSoftware.ts DevSoftwareInfo factory
createIOChannel.ts IOChannel factory
createEquipmentVersion.ts EquipmentVersion factory
createEquipmentParameter.ts EquipmentParameter factory
export/ Export provider framework
AbstractExportProvider.ts Base class for providers
BaseExportProvider.ts Template-method export pipeline
BaseDiagnosticProvider.ts Diagnostic-emitting base
ClassifiedVariables.ts Variable classification helpers
DiagnosticBuilder.ts Fluent diagnostic builder
ExportContext.ts Per-export context
FormatAdapter.ts Output format adapter contract
adapters/ Text and XML format adapters
import/ Import provider framework
AbstractImportProvider.ts Base class for importers
support/ Action-support helpers
actionSupport.ts Support verdict helpers
unsupportedActions.ts Placeholder-comment helpers
translation/ Translation provider base
BaseTranslationProvider.ts Base class for translation providers
runtime/ Host runtime loading
loadHostRuntime.ts Routes runtime values to the host
validation/ Runtime validation
TypeGuards.ts Type guard functions
vscode/ VS Code helpers
getAutomationViewAPI.ts Retrieve the AV extension APIVersioning
@automationview/api follows semver. Plugins must keep their declared
dependency in lockstep with the host extension on every minor or major bump
(patch releases are drop-in). See docs/API_BUMP_POLICY.md in the
automationview-extension repo for the full policy.
4.0.0 - breaking changes
One removal on a published type forces this major; everything else in 4.0.0 is additive.
ActionDefinition.parameterBindingis removed. The binding moved onto each descriptor: setbinding: 'positional' | 'keyed' | 'field'on the entries ofparameters[]. A descriptor withoutbindingkeeps the historical reading,keyed, so a plugin that never declaredparameterBinding- which is every plugin inautomationview-plugins- needs no change at all.One action may now mix bindings. A
positionaldescriptor addressesoperands[k]wherekcounts POSITIONAL descriptors only, so afield-bound input declared before it does not shift the operand index the action class reads.The retentive timer and the four counters gained the boolean input their runtime always read:
RTO/CTU/CTURanRreset slot,CTD/CTDRanLDload slot, all optional and all bound tooperands[0].
Raise both your @automationview/api dependency and your plugin's
REQUIRED_HOST_API_RANGE to ^4.0.0. Full guide:
docs/migration-4.0.md in the automationview-extension repo.
3.0.0 - breaking changes
Two removals on published types force this major; everything else in 3.0.0 is additive.
ActionDefinition.parameterKindand theActionParameterKindenum are removed. Declareparameters[]and setbinding: 'positional' | 'keyed' | 'field'on each descriptor instead (in 3.0.0 this wasparameterBindingon the definition; see 4.0.0 above). A descriptor withoutbindingkeeps the historical reading,keyed.'ARRAY'is no longer a data type:TypeCategoryhas lost its'ARRAY'member and is now'PRIMITIVE' | 'COMPOUND' | 'STRUCT' | 'ENUM'. Array-ness is a modifier (arrayBounds) beside an elementdataType- see Arrays.ARRAYsurvives as a reserved name only.
Raise both your @automationview/api dependency and your plugin's
REQUIRED_HOST_API_RANGE to ^3.0.0. Full guide:
docs/migration-3.0.md in the automationview-extension repo.
License
PRIVATE @RCAutomSolutions
