Extensions (.vndtool)
Package layout and manifest.json of a tool extension, lifecycle, tool windows, the complete program interface ctx, PHP server parts, building, gallery upload, security rules and a complete Hello extension.
Overview#
An extension is an additional tool that is not part of the program. It is available as a *.vndtool file (a ZIP file) and, after installation, appears as a tile in the Tools window (menu Tools › Open VN tools). It runs in all editions and can be removed again. An extension can
- open its own window with any interface (
ctx.openToolWindow), - read the project and change it within a fixed scope (
ctx.project,ctx.blocks), - bring its own blocks and insert them (
ctx.blocks.importPackage), - put files and code into the finished website on export, including PHP server parts (
ctx.project.exportContribution), - store credentials safely in the program profile (
ctx.project.secrets), - use the AI accesses entered in the program (
ctx.project.ai).
Installation and location: “+ Install extension…” in the Tools window (or drag the file onto the window, or install from the tool gallery). The program unpacks the package into <program profile>/extensions/<id>/ (under Windows %APPDATA%), not into the project. When you pass a project on, extensions are not included; a program update leaves them untouched.
Package layout#
manifest.json Pflicht, steht im ZIP ganz vorn
tool.js Pflicht (oder die Datei, die manifest.json unter "main" nennt): ES-Modul
payload.js optional: PHP-/Dateiinhalte für den Export als JavaScript-Modul (erzeugt von make-payload.py)
dom.js optional: Hilfsfunktionen für die Oberfläche (h(), clear(), debounce(), sleep())
style.css optional: Stil des Werkzeugfensters
*.vndext optional: mitgelieferte Bausteine (Paketformat siehe Kapitel Pakete)
thumbnail.jpg Vorschau für die Galerie (nur dort gelesen; muss IM Paket liegen)
icon.svg, ... beliebige Beigaben (Bilder, weitere .js-Module, Texte)Example vn-ical.vndtool (verbatim from the ZIP): manifest.json, dom.js, ical-block.vndext, payload.js, style.css, thumbnail.jpg, tool.js. The package of the example extension is even smaller: manifest.json, icon.svg, tool.js.
manifest.json#
Syntax
{
"id": "hallo-erweiterung",
"name": "Hallo-Erweiterung",
"name_en": "Hello extension",
"name_fr": "Extension Bonjour",
"version": "1.0.0",
"icon": "HI",
"description": "Zeigt die Seiten des Projekts, merkt sich einen Gruß und legt ihn beim Export als Datei ab.",
"description_en": "Shows the pages of the project, remembers a greeting and writes it to a file on export.",
"description_fr": "Affiche les pages du projet, mémorise un message d'accueil et l'écrit dans un fichier lors de l'export.",
"author": "Beispiel GmbH",
"main": "tool.js"
}Fields
| Field | Type | Default | Meaning |
|---|---|---|---|
id | text | – | Required. 2–48 characters, a-z, 0-9, -, _, starts with a letter or digit. It is the folder name in the profile and the identifier for settings, secrets and the export contribution. Must never change: otherwise an update is installed as a second tool. IDs of built-in tools are reserved (installation is rejected and the files are removed again) |
name | text | – | Required. Name of the tile (German) |
name_en, name_fr, name_<language> | text | – | Name in another program language. The version of the program language applies, otherwise the English one, otherwise the German one. Only fields of the form name_xx with two to three letters, at most 400 characters |
description, description_<language> | text | empty | Description on the tile; same language rule |
version | text | empty | Shown on the tile and used for the update comparison with the gallery. Increase it with every change |
icon | text | abbreviation from the name | Short character in the blue symbol of the tile, at most 4 characters (emoji too). Without a value the program forms an abbreviation from the first letters of the first words (“VN SEO” → “SE”) |
author | text | empty | Author |
main | text | tool.js | Program file. Must be in the package and stay inside the folder |
tool.js#
An ES module. export default supplies an object with run(ctx) or a function directly. run is executed on every click on the tile.
Syntax
export default {
run(ctx, opts) {
// Oberfläche bauen, ctx.openToolWindow(titel, element, { large }) aufrufen
},
};Further files can be imported normally (import { h } from './dom.js?v=4'). If export default is missing or is neither an object with run nor a function, the tile stays with “⚠ Could not be loaded” and the message.
payload.js and dom.js#
These are naming conventions of the existing extensions, not mandatory files: payload.js exports PAYLOAD, an object { "api.php": "<?php …", "lib.php": "…" } with the files of the server part (see PHP server parts). dom.js contains the helper h('div.klasse#id', { attr, onclick, html }, kinder…), clear(el), debounce(fn, ms) and sleep(ms); it is identical in all extensions (template: extensions-src/vn-ical/dom.js).
Lifecycle#
- Start: The program reads
ext:list(all folders underextensions/with a validmanifest.jsonwhoseidmatches the folder name) and loads eachmainviaimport()with the address…/tool.js?v=<modification time of the file>. If that succeeds, the tool is entered in the registry with name, description, version and symbol; otherwise as broken (red message, removable). - Click on the tile:
run(ctx, opts)is called.ctxis a separate view for each extension: additionallyctx.extensionand actx.projectlimited to its ownid. - Window:
ctx.openToolWindowcloses an already open tool window and the tile overview and shows the new window (see below). - Installation, update, removal: On installation the package is first unpacked into an intermediate folder, then it replaces an existing version; a broken package never destroys a running extension. Removal (trash icon on the tile) deletes the folder. After an update the program reports “Please restart VN-Designer so that all parts of the new version are loaded”.
Tool window#
ctx.openToolWindow#
Opens the movable window of the extension at the bottom right (drag by the header, close with ✕). There is always only one tool window; a new call replaces the old one.
Syntax
ctx.openToolWindow(titel, element, { large: true })| Parameter | Type | Meaning |
|---|---|---|
titel | text | Title in the header of the window |
element | DOM element | Content. The program attaches it to the window; you build it yourself |
large | boolean | Larger, freely resizable window (up to 1000 × 820 px, centered at the top), without its own inner padding; for tools with a multi-column interface |
Example
const box = document.createElement('div');
box.textContent = 'Hallo ' + (ctx.projectDir || '(kein Projekt)');
ctx.openToolWindow('Mein Werkzeug', box);ctx.closeToolWindow#
ctx.closeToolWindow() closes the window. Returns: nothing.
ctx.askConfirm#
Confirmation dialog in the style of the program. await ctx.askConfirm(text) returns true (yes) or false. Use it for irreversible actions instead of window.confirm.
The interface ctx#
ctx has the following entries. If an entry is missing (older program version), check for it before using it (if (!ctx.project || !ctx.project.exportContribution) …) and report that in a friendly way.
| Entry | Meaning |
|---|---|
ctx.projectDir | Folder of the open project (text) or null |
ctx.getPages() | The pages of the project with all blocks, including unsaved changes. These are the working objects of the editor, not copies: read only. A page has, among others, id, name, slug, blocks, publish; a block has id, alias, schemaEntry, values |
ctx.getGlobalBlocks() | The site-wide blocks (menu, footer), same form as blocks of a page, also read only |
ctx.switchToPage(id) | Switches the editor to the page with this id |
ctx.askConfirm(text) | see above |
ctx.openToolWindow, ctx.closeToolWindow | see above |
ctx.extension | { id, version, baseUrl } of the extension itself; baseUrl is the address of the extension folder with a trailing slash |
ctx.project | Project interface, see below (copies for reading, allowlist for changing) |
ctx.blocks | Block interface, see below |
In addition, window.vnDesigner is available (program bridge to the main process). The extensions of the program use: saveAsset(projectDir, unterordner, dateiname, arrayBuffer, { keepName }) (stores a file under assets/<subfolder>/ in the project, returns { filename, path, relativePath, fileUrl }; image, font, css and js files up to 15 MB are allowed), listAssetImages(projectDir) (images under assets/images/), openExternal(url) (only http/https in the default browser), loadSmtpConfig(projectDir) (the SMTP credentials entered in the program), netCheckUrl({ url, method, timeoutMs }) (checks an address without internal targets), downloadGoogleFont(…) and vnpdfSave(…). These functions belong to the program and may change; extensions that you pass on should stick to ctx where possible.
ctx.project.getInfo#
A copy of the project data.
Syntax and return value
const info = ctx.project.getInfo();
// {
// projectDir, title, activePageId,
// site: { siteUrl, lang, metaDescription, favicon, seo, translateActive, cookieConsentActive, localFonts },
// pages: [ { id, name, slug, seoTitle, metaDescription, ogImage, lang, publish, seo, headExtra, bodyExtra, blockCount } ]
// }seo is null as long as the SEO tool has not set anything. localFonts is the number of custom fonts.
ctx.project.buildFiles#
Builds the finished pages in memory, exactly as the export would write them, without saving anything (only ticked pages).
const r = await ctx.project.buildFiles();
// { files: [ { filename: 'index.html', pageId, html } ], extraFiles: [ { filename: 'sitemap.xml', text } ], css: '…fertiges style.css…' }extraFiles contains sitemap.xml, robots.txt and llms.txt, as far as the SEO tool switches them on. The contribution of the extensions (files, head, bodyEnd) is not included in buildFiles().
ctx.project.updatePage#
ctx.project.updatePage(id, patch) changes fields of a page and returns true (page found) or false. Only these fields are allowed, each text with this maximum length: seoTitle (300), metaDescription (600), ogImage (500), lang (20), headExtra (400000), bodyExtra (400000); plus seo (object, is normalized; null removes it). The change takes effect immediately in the project; the user then saves as usual.
ctx.project.updatePage(info.pages[0].id, { seoTitle: 'Startseite | Mein Betrieb', metaDescription: 'Kurzbeschreibung …' });ctx.project.updateSite#
ctx.project.updateSite(patch) changes the website settings: siteUrl (300 characters), metaDescription (600), lang (20) and seo (object or null). Returns true.
ctx.project.getGlobalHtml and setGlobalHtml#
getGlobalHtml() returns { headExtra, bodyStart, bodyExtra }, the “Global HTML insertions” (gear icon in the bar). setGlobalHtml(patch) changes one or more of these fields (text, at most 400000 characters each) in one undo step and returns true. The field for code before the doctype (doctypeExtra) is not reachable.
ctx.project.listImages and setImageAlt#
await ctx.project.listImages() returns all images of the pages and the site-wide blocks with their effective alt text:
// [ { blockId, blockLabel, pageId, pageName, global, metaId: 'k:photo', src: 'file:///…/foto.jpg', alt: '' } ]ctx.project.setImageAlt(blockId, metaId, alt) sets the alt text (at most 300 characters) and returns true.
ctx.project.assetSizes#
await ctx.project.assetSizes(['assets/images/foto.jpg']) returns the file sizes below assets/ and publish/: { "assets/images/foto.jpg": { "size": 8228 }, "assets/nix.png": null }. At most 2000 paths; other paths result in null.
ctx.project.addPage#
Creates a new page with one “Custom HTML code” block.
const r = ctx.project.addPage({ name: 'Impressum', slug: 'impressum.html', html: '<section><h1>Impressum</h1></section>', label: 'Impressum' });
// { ok: true, pageId } | { ok: false, exists: true, pageId } | { ok: false, error: 'Ungültiger Dateiname' }slug must match ^[a-z0-9_-]{1,60}\.(html|php)$; html at most 400000 characters. An existing page is never overwritten (then exists: true). The page is not opened.
ctx.project.newEmptyPage#
Creates an empty page and switches to it: ctx.project.newEmptyPage({ name, slug }) returns { ok, pageId, slug }. The file name is made unique if necessary (-2, -3 …). Afterwards, blocks inserted with ctx.blocks.addFromCatalog end up on this page.
ctx.project.findInBlocks#
await ctx.project.findInBlocks(muster) searches for a pattern (text of a regular expression, case-insensitive, at most 400 characters) in the finished HTML and CSS of all blocks:
// [ { pageId, pageName, global, blockId, blockLabel, where: ['HTML', 'CSS'], sample } ]ctx.project.selectBlock and showPage#
ctx.project.selectBlock(pageId, blockId) switches to the page, selects the block and scrolls it to the center. await ctx.project.showPage(pageId) shows a page and waits until the canvas has drawn all its blocks; a prerequisite for measurements on the finished rendering. ctx.project.canvas() returns the element of the canvas (read only, e.g. getComputedStyle); every block is there in .canvas-block[data-block-id].
ctx.project.colorUsage and replaceColors#
ctx.project.colorUsage() returns all adjustable colors:
// [ { color: '#e6f4f1', art: 'bg', ort: 'Hintergrund', pageId, pageName, global, blockId, blockLabel } ]
// art: 'field' | 'bg' | 'text' | 'icon' | 'site'Covered are color fields and backgrounds of the blocks, color: in formatted text, symbol colors, the Custom CSS and the back-to-top button. Colors that are fixed in the theme CSS are missing.
ctx.project.replaceColors({ '#e6f4f1': '#ffeecc' }, { blockIds, site }) replaces in one pass (without chain effect A→B→C) and in one undo step. blockIds restricts it to these blocks; site: true includes the Custom CSS and the back-to-top button. Anchors (href="#abc"), selectors, strings and url(#…) remain untouched. Returns { changed, blocks } (in the test: { "changed": 2, "blocks": 2 }).
ctx.project.settings#
The extension's own settings, stored in the project (siteSettings.extensions[<id>].settings).
const s = ctx.project.settings.get(); // Kopie oder null
ctx.project.settings.set({ gruss: 'Hallo' }); // ersetzt alles; set(null) löschtThe values must be JSON-compatible. The user still has to save the project.
ctx.project.exportContribution#
What the extension contributes on export.
Syntax
ctx.project.exportContribution.set({
head: '<link rel="stylesheet" href="assets/hallo-erweiterung/stil.css">',
bodyEnd: '<script src="assets/hallo-erweiterung/skript.js"></script>',
files: [ { path: 'assets/hallo-erweiterung/gruss.txt', text: 'Hallo\n' } ],
});
ctx.project.exportContribution.get(); // Kopie oder null
ctx.project.exportContribution.set(null); // Beitrag entfernenFields and limits
| Field | Meaning |
|---|---|
head | Code at the end of <head> on every page (after the stylesheet, before the code of the global insertions); at most 20000 characters |
bodyEnd | Code at the end of <body> (after the program's scripts, before the code of the global insertions); not blocked by the cookie notice; at most 20000 characters |
files | Text files { path, text }. The path must be assets/<own id>/… (characters A-Za-z0-9._/-, at most 120 after the identifier, no ..). At most 30 files (further ones are silently cut off), at most 400000 characters per file |
A violation of the path or file size rules throws an exception (“Invalid file in the export contribution”). The contribution is stored in the project file and only output while the extension is installed and loaded. If you set it to null or remove the extension, the next export removes the previously written files and empty folders (confirmed in the test). Files already on the server are not deleted by the program.
In files[].text the export replaces the placeholders {{secret:NAME}} and {{secret-php:NAME}} with secrets, see the next entry. There is no replacement in head and bodyEnd.
ctx.project.secrets#
Secrets (e.g. password check values) are stored in the program profile, not in the project, encrypted if Windows offers that.
await ctx.project.secrets.set('hash', pruefwert); // { ok: true }; set(name, null) oder '' löscht
const namen = await ctx.project.secrets.names(); // ['hash', 'salt']name: 1–40 characters from A-Za-z0-9_; wert: text, at most 500 characters. Secrets can never be read back; only names() reveals which ones exist. The export inserts them into files of the contribution:
| Placeholder | Replacement |
|---|---|
{{secret:NAME}} | the value unchanged |
{{secret-php:NAME}} | the value with backslash, double quotes and dollar signs escaped (\\, \", \$), for a PHP string in double quotes |
A missing secret results in an empty text.
Example (from vn-ical, shortened): The administration password never leaves the program in plain text. The tool computes the salt and the PBKDF2 check value and stores both as secrets; the file admin-config.php in the contribution contains only the placeholders.
const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', salt: new TextEncoder().encode(salz), iterations: 100000, hash: 'SHA-256' }, key, 256);
await ctx.project.secrets.set('salt', salz);
await ctx.project.secrets.set('hash', hex(bits));
ctx.project.exportContribution.set({ files: [
{ path: 'assets/vn-ical/admin-config.php',
text: '<?php\n$admin_pbkdf2_salt = "{{secret-php:salt}}";\n$admin_pbkdf2_hash = "{{secret-php:hash}}";\n' },
] });ctx.project.ai#
Uses the AI accesses entered in the program (Settings › AI). The text leaves the computer towards the provider. Show this to the user.
| Entry | Meaning |
|---|---|
await ai.providers() | The configured providers: [ { id, label } ] (empty if none is entered) |
await ai.ask({ providerId, systemPrompt, userPrompt, model, onDelta, signal, onThink }) | Asks a question; returns the answer text. model overrides the model for this request only. onDelta(chunk, total) reports the answer progressively (streaming; an answer cut off at the length limit is then not thrown as an error, check this yourself). signal is an AbortSignal that really aborts the request. onThink(characters) reports the thinking phase of local AI models (thinking is switched off for tools) |
ai.openSettings() | Opens the dialog for the AI keys |
ai.streaming, ai.thinking | true: ask supports onDelta, signal and onThink (feature test) |
ai.speech, await ai.speechProvider() | Speech input: speechProvider() returns { id, label } of the provider (Groq first, then ChatGPT) or null |
await ai.transcribe({ audio, language, prompt, signal }) | Recording (Blob, e.g. audio/webm) → recognized text. Without Groq or ChatGPT access it throws an exception |
const anbieter = await ctx.project.ai.providers();
if (!anbieter.length) { ctx.project.ai.openSettings(); return; }
const text = await ctx.project.ai.ask({ providerId: anbieter[0].id, systemPrompt: 'Antworte kurz.', userPrompt: 'Schlage einen Seitentitel vor.' });ctx.blocks.importPackage#
Imports a block package (.vndext with one component, as an ArrayBuffer) and inserts it on the current page. The program reports errors itself.
const res = await fetch(ctx.extension.baseUrl + 'ical-block.vndext');
const ok = await ctx.blocks.importPackage(await res.arrayBuffer(), { position: 'end' }); // true | falseopts.position: 'end' (at the end of the page), 'start', 'after' (after the selected block), a number (position, 0 = very top); without a value, after the selected block. A package with several components is not supported (use importToLibrary for that). A site-wide block (global) replaces the existing one of its group.
ctx.blocks.importToLibrary#
Puts a package into the project's library, not onto the page. Theme packages go in with all their blocks; an identical alias replaces the existing entry.
const r = await ctx.blocks.importToLibrary(buffer); // { ok: true, count: 3 } | { ok: false, message }Nothing is displayed; the extension shows the result itself.
ctx.blocks.findByAlias and setValues#
ctx.blocks.findByAlias(alias) finds the blocks of this block type on the current page: [ { id, selected, values } ] (values is a copy, selected is true for the selected block). The alias is that of the package (for a single block params.alias, for a theme package <alias>-<folder>). await ctx.blocks.setValues(blockId, patch) sets values of the Properties panel (patch = { schluessel: wert }), redraws the block and creates an undo step; returns true/false.
const liste = ctx.blocks.findByAlias('vn-ical');
if (liste.length) await ctx.blocks.setValues((liste.find((b) => b.selected) || liste[0]).id, { accent: '#15803d' });ctx.blocks.describe, selected, pageBlocks#
ctx.blocks.describe(blockId) and ctx.blocks.selected() (selected block or null) describe the properties of a block as the panel knows them; ctx.blocks.pageBlocks() lists the blocks of the current page.
ctx.blocks.describe(id);
// { blockId, label, alias, isGlobal, groups: ['Größe', …],
// fields: [ { key, label, type, group, options?, min?, max?, step?, condition? } ],
// values: { paddingTop: '8', showImage: true, bg: { type: 'color', value: '#e6f4f1', parallax: false } } }
ctx.blocks.pageBlocks(); // [ { blockId, label, alias } ]type is text, textarea, checkbox, color, range, select (options: [[value, label], …]), image or background. Values that are too large (over 2000 characters) are missing in values.
ctx.blocks.catalog and addFromCatalog#
await ctx.blocks.catalog() lists all insertable blocks (themes folder with the start theme, and the library): [ { key, source: 'theme'|'library', theme, title, group, once } ] (once = 'menu'/'footers' for site-wide blocks, otherwise empty). await ctx.blocks.addFromCatalog(key, opts) inserts one of them (opts.position as with importPackage) and returns the identifier of the block or null.
ctx.blocks.texts#
Read and write the editable texts of the current page (including menu and footer).
const alle = ctx.blocks.texts.list();
// [ { blockId, blockLabel, blockAlias, textId: 't0', tag: 'a', html: 'Mein Betrieb', text: 'Mein Betrieb', isLink: true } ]
const n = await ctx.blocks.texts.set([ { blockId: alle[0].blockId, textId: alle[0].textId, text: 'Neu & besser' } ]); // 1list() returns the texts in document order, only from blocks that are currently on the canvas. set(entries) sets for each entry either html (is cleaned as when typing: inline formatting and links) or text (plain text, characters escaped, line breaks become <br>), redraws the blocks, creates an undo step and returns the number of changed texts.
ctx.blocks.images#
ctx.blocks.images.list() returns the image slots of the blocks on the page: [ { blockId, blockLabel, slot, kind: 'field'|'background'|'free', label, url, alt, w, h } ]. slot is k:<field> (image field in the panel), b:<field> (background image) or f:<identifier> (free image in the block); w/h the displayed size in px. await ctx.blocks.images.set([ { blockId, slot, url, alt } ]) sets images (url is the fileUrl of a file saved in the project, alt optional, at most 300 characters) in one undo step and returns the number of images set.
Further entries of ctx.blocks#
| Entry | Meaning |
|---|---|
addBlock(result, opts) | Inserts a finished import result ({ status: 'ok', alias, schemaEntry, message }). It requires a schemaEntry generated by the program; extensions use importPackage |
findGalleries(), updateGallery(blockId, result) | Belong to the built-in tool VN Gallery (find gallery blocks and replace their images); not meant for your own blocks |
anim.targetAt(el), anim.selectedTargets(), anim.set(blockId, entries), anim.play(blockId, cfgs), anim.mark(blockId, ids) | Belong to the built-in tool VN Animation (animations for texts and images); internal interface, may change |
PHP server parts#
An extension can provide server-side functions on the finished website (appointment calendar, guestbook, statistics …). The pattern that all existing extensions use:
- The PHP files are in the source folder of the extension under
payload/. A script (make-payload.py) reads them and writespayload.js: a module that exportsPAYLOADas an object{ "api.php": "…", "lib.php": "…" }. Files underdata/anduploads/as well asconfig.phpstay out, because they only come into being on the server. tool.jsimportsPAYLOADand builds the export contribution from it: each file as{ path: 'assets/<id>/<name>', text }, plus the generatedconfig.phpwith the user's settings and anadmin-config.phpwith secret placeholders.- On export the program writes the files to
publish/assets/<id>/. The user uploadspublish/like any website.
Example (from vn-ical, shortened)
import { PAYLOAD } from './payload.js?v=5';
const ID = 'vn-ical';
function buildContribution(s) {
const base = 'assets/' + ID + '/';
const files = Object.keys(PAYLOAD).map((name) => ({ path: base + name, text: PAYLOAD[name] }));
files.push({ path: base + 'config.php', text: buildConfigPhp(s) });
files.push({ path: base + 'admin-config.php', text: buildAdminConfig(s) });
return { files };
}
ctx.project.exportContribution.set(s.enabled ? buildContribution(s) : null);Rules for server parts:
- Limits: at most 30 files per extension, 400000 characters per file. If the server part is larger, merge files. The contribution is stored in the project file (
siteSettings.extensions[<id>].contribution) and makes it correspondingly larger. - Protect the
data/folder: The program does not write a.htaccessfor contributions. The PHP code creates it itself (vn-ical:Require all deniedincluding a fallback for older Apache versions, on first access inlib.php). Never output paths in messages. - Generate the configuration on export: The user's settings do not belong in fixed files.
tool.jsrebuildsconfig.phpfrom the settings every time (as a nowdoc with JSON, so that nothing has to be escaped) and inserts secrets via placeholders. - Sending e-mail: On export the program writes the SMTP credentials entered in the program to
assets/vn-shared/config.php(only if SMTP is set up); PHP parts read them withdirname(__DIR__) . '/vn-shared/config.php'(variables$smtp_host,$smtp_port,$smtp_encryption,$smtp_username,$smtp_password,$smtp_from_email,$smtp_from_name,$hmac_secret). See Publishing. - PHP 7.3 and newer, also 8.x. Check every file with
php -land test withphp -S 127.0.0.1:<port>against the exported folder. - Never ship the database and visitor data in the contribution; passwords only as a PBKDF2 check value; validate input, escape output, CSRF protection, session cookie
HttpOnly/SameSite, limit login attempts; noeval, noinnerHTMLwith raw data. - Data protection: Do not load scripts, fonts or images from third-party servers in
head/bodyEndor in the page's interface.
Blocks inside an extension#
An extension ships blocks as .vndext files in the package (block/ in the source folder, packed by make-payload.py into <name>-block.vndext). The tool inserts them with importPackage and later changes them with findByAlias and setValues. The alias in the block's params.json is the identifier for that (vn-ical). The block contains only the interface and the script of the page; it fetches the data via the files in the contribution. Texts that later go into the page are taken as a property of the block (never raw into a data-…="{{x}}"; use {{vnEnc(x)}}).
Build, test, deliver#
Build the package
python extensions-src/build-ext.py extensions-src/mein-werkzeug dist-ext/mein-werkzeug.vndtoolbuild-ext.py requires id and name in manifest.json, puts the file manifest.json at the very front of the ZIP and packs all other files of the folder. A file .vndignore (one name per line, # for comments) names files and folders that should not go into the package (source folders payload/, block/, tests/, make-payload.py). If a script such as make-payload.py comes first, run it before packing.
Test
- Install the package in the Tools window, click the tile. An error in
tool.jsleaves the tile with ⚠ and the message; that way customers can remove it. - Play through each function individually, including error cases (no project open, older program version).
- Export and check the result in
publish/in the browser or with PHP; look for the file and thebodyEndcode of the extension. - Set the contribution to
nulland export again: the files must disappear.
The program checks on installation: manifest.json must be present and contain valid JSON with a valid id and a name; the program file must be in the package. Paths in the package that lead out of the folder (.., absolute paths, drive letters) are skipped. At most 40 MB are unpacked.
Gallery (two servers, same packages)
| Gallery | Format and rules |
|---|---|
Tool gallery (gallery-server-tools, tab “Tools”) | Upload a .vndtool (a real ZIP with a valid manifest.json and program file, at most 100 MB). The manager reads name, version, description (DE/EN) and author from manifest.json; the identifier is the id. Preview: an uploaded image (PNG/JPG/GIF/WebP up to 2 MB) or thumbnail.jpg in the package. New tools are a draft first; only “Visible” releases them. Paid tools have a price, purchase link and product identifier in the shop; without a valid purchase code the server does not deliver the package |
Block gallery (gallery-server) | Accepts .vndext and .vndtool. An extension needs manifest.json (id, name, optionally version, description, author) and tool.js; preview as for blocks (thumbnail, thumb, preview … as .jpg/.png in the package) |
Security rules#
Extensions are program code with the rights of the program. The program therefore does not offer an open marketplace; packages from the gallery are installed after a confirmation prompt.
For authors:
- No third-party libraries, no CDN addresses, no web fonts: ship everything yourself.
- Validate and sanitize input; no
eval, noinnerHTMLwith raw data (text viatextContentor through a helper such ash()). - Credentials only via
ctx.project.secrets, never in the project, never insettings, never in a file that the user passes on. - Contribution only under
assets/<own id>/…; the program allows no other paths. - With
ctx.project.ai, text leaves the computer: tell the user beforehand. - The program hands extensions only an allowlist of functions; the objects of
ctx.getPages()are, however, live working objects. Never change them directly.
The program itself limits: ID format, zip-slip protection when unpacking, intermediate folder with replacement, 40 MB, path check in the contribution, secrets never readable back, names and length of the secrets and the settings.
Example: the Hello extension#
A complete extension with three files. It shows the pages of the project, remembers a greeting in the project settings and outputs it on export as the file assets/hallo-erweiterung/gruss.txt and as a comment at the end of <body>. It was installed in a program instance and played through: show pages, remember, set export contribution, export (file and comment were in publish/), remove contribution, export again (file and folder had disappeared).
manifest.json
{
"id": "hallo-erweiterung",
"name": "Hallo-Erweiterung",
"name_en": "Hello extension",
"name_fr": "Extension Bonjour",
"version": "1.0.0",
"icon": "HI",
"description": "Zeigt die Seiten des Projekts, merkt sich einen Gruß und legt ihn beim Export als Datei ab.",
"description_en": "Shows the pages of the project, remembers a greeting and writes it to a file on export.",
"description_fr": "Affiche les pages du projet, mémorise un message d'accueil et l'écrit dans un fichier lors de l'export.",
"author": "Beispiel GmbH",
"main": "tool.js"
}tool.js
// tool.js — Hallo-Erweiterung: Projekt lesen, Einstellung merken, Export-Beitrag setzen.
const ID = 'hallo-erweiterung';
/** el('div.klasse', { onclick: fn }, 'Text', kind …) — kleiner Helfer statt innerHTML */
function el(spec, attrs, ...kids) {
const [tag, ...cls] = spec.split('.');
const n = document.createElement(tag);
if (cls.length) n.className = cls.join(' ');
Object.keys(attrs || {}).forEach((k) => {
if (k.startsWith('on')) n.addEventListener(k.slice(2), attrs[k]);
else n.setAttribute(k, attrs[k]);
});
kids.forEach((x) => n.append(x));
return n;
}
export default {
run(ctx) {
const api = ctx.project;
const win = (inhalt) => ctx.openToolWindow('Hallo-Erweiterung', inhalt);
// Ältere Programmversionen kennen ctx.project nicht: freundlich melden statt abstürzen
if (!api || !api.exportContribution) { win(el('p', {}, 'Dafür braucht es eine neuere Version von VN-Designer (ab 1.1.55).')); return; }
if (!ctx.projectDir) { win(el('p', {}, 'Bitte zuerst ein Projekt öffnen.')); return; }
const saved = api.settings.get() || {};
const input = el('input', { type: 'text', value: saved.gruss || 'Hallo Welt' });
const out = el('pre.hallo-out', {});
const say = (text) => { out.textContent = text; };
win(el('div.hallo-root', {},
el('link', { rel: 'stylesheet', href: ctx.extension.baseUrl + 'style.css' }),
el('label', {}, 'Gruß ', input),
el('button', { onclick: () => { api.settings.set({ gruss: input.value }); say('Gespeichert (Projekt speichern nicht vergessen).'); } }, 'Merken'),
el('button', { onclick: () => {
const info = api.getInfo();
say(info.title + ': ' + info.pages.map((p) => p.name + ' (' + p.slug + ')').join(', '));
} }, 'Seiten zeigen'),
el('button', { onclick: () => {
const text = String(input.value).replace(/[<>&-]/g, ' ').slice(0, 200);
api.exportContribution.set({
bodyEnd: '',
files: [{ path: 'assets/' + ID + '/gruss.txt', text: text + '\n' }],
});
say('Export-Beitrag gesetzt. Er gilt beim nächsten Export.');
} }, 'Beim Export mitgeben'),
el('button', { onclick: () => { api.exportContribution.set(null); say('Beitrag entfernt.'); } }, 'Beitrag entfernen'),
out,
));
},
};style.css
.hallo-root { display: grid; gap: 0.6rem; font-size: 0.85rem; }
.hallo-root input { width: 100%; box-sizing: border-box; }
.hallo-root button { cursor: pointer; }
.hallo-out { margin: 0; white-space: pre-wrap; min-height: 2.4em; }Build and install
python extensions-src/build-ext.py extensions-src/hallo-erweiterung dist-ext/hallo-erweiterung.vndtoolThen “+ Install extension…”, click the tile “Hello extension”. After “Beim Export mitgeben” and an export, the result contains at the end of body:
</body>