Skip to the content
Gridkiln
Menu
Guide contents

Guide Plugins

Worked example: the text-tools plugin

fixtures/plugins/text-tools/ in the source code is a small plugin with two step types, one of each kind a plugin can give: upper, which compiles to SQL, and slugify, which runs code over the rows. It has two files, and this page explains every line of both, then installs it, uses it and tests it.

text-tools/
  plugin.yaml   what the plugin is and what it adds
  index.mjs     the code

plugin.yaml#

gridkiln: plugin
schemaVersion: 1
id: example.text-tools
name: Text tools
version: 1.0.0
description: Two step types, one of each kind a plugin can give - one that is plain SQL and one that runs code.
author: Gridkiln examples
licence: MIT
main: index.mjs
contributes:
  steps:
    - name: upper
      title: Upper case (as SQL)
      family: clean
      configSchema:
        type: object
        properties:
          column:
            type: string
            minLength: 1
            title: Column
        required: [column]
        additionalProperties: false
    - name: slugify
      title: Make a slug
      family: calc
      configSchema:
        type: object
        properties:
          column:
            type: string
            minLength: 1
            title: Column
          into:
            type: string
            minLength: 1
            default: Slug
            title: New column
        required: [column]
        additionalProperties: false

Line by line:

  • gridkiln: plugin and schemaVersion: 1 say what kind of file this is and the version of its format. Both may be left out; the app fills them in.
  • id: example.text-tools is the plugin’s identity: lower-case letters, digits, dots, dashes and underscores. It names the plugin’s folder once installed, and every pipeline that uses one of its steps refers to it by this id, so it must not change between versions.
  • name is what people see in Settings › Plugins and the install dialog; description is the sentence under it.
  • version: 1.0.0 is a semantic version. Installing a higher version replaces the installed one in one step. There is no requires line, so it installs in any version of the app.
  • author and licence are shown as they are.
  • main: index.mjs is the entry module, a file inside the folder with an extension Node runs as an ES module.
  • There is no capabilities line, so the plugin asks for nothing beyond its own folder and the tables it is handed: no network, no other files, no other programs. The install dialog says “Nothing beyond its own folder and the tables it is handed.” and asks no one to trust it with more.
  • contributes.steps lists the two step types. Each has:
    • name, which must match a key under steps in the code exactly (upper, slugify), and is what pipelines store;
    • title, what the step is called in the app;
    • family, the step family it belongs with (clean for the upper-case step, calc for the slug, which adds a calculated column);
    • configSchema, a JSON Schema for the step’s settings. upper needs a column, a non-empty string. slugify needs a column, and takes an optional into that defaults to Slug. additionalProperties: false refuses settings with a misspelt name rather than ignoring them. The app checks the settings against this schema, and fills in into: Slug when it is left out, before calling the plugin, so the code never sees settings that do not fit.

index.mjs#

// Example step types (P8-05): `upper` compiles to SQL (it stays inspectable and runs inside the engine's query);
// `slugify` runs code over the rows (the table crosses into the plugin's process and back).
import { PluginError, definePlugin } from '@gridkiln/plugin-api';

const quote = (name) => `"${String(name).replaceAll('"', '""')}"`;

function requireColumn(input, column) {
  if (!input.columns.some((c) => c.name === column)) {
    throw new PluginError(`There is no column called ${column} in the table.`);
  }
}

function slug(text) {
  return String(text)
    .normalize('NFKD')
    .replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

export default definePlugin({
  steps: {
    upper: {
      schema: (config, [input]) => {
        requireColumn(input, config.column);
        return input.columns;
      },
      compileSql: (config, [input]) => `SELECT * REPLACE (upper(${quote(config.column)}) AS ${quote(config.column)}) FROM ${input.name}`,
    },
    slugify: {
      schema: (config, [input]) => {
        requireColumn(input, config.column);
        return [...input.columns, { name: config.into, type: 'text' }];
      },
      transform: (config, [table]) =>
        table.rows.map((row) => ({ ...row, [config.into]: row[config.column] === null ? null : slug(row[config.column]) })),
    },
  },
});

Piece by piece:

  • The import. definePlugin marks the default export as a plugin definition and returns it unchanged. PluginError is an error whose message is shown to the user as written. Inside the app, @gridkiln/plugin-api always resolves to the app’s own copy, so the folder needs no node_modules.
  • quote writes a column name as a SQL identifier, doubling any " inside it. Column names come from the data, so they must never be pasted into SQL unquoted.
  • requireColumn checks that the column the settings name is in the table. When it is not, it throws a PluginError with a sentence the user can act on: “There is no column called Customer in the table.” Anything else a plugin throws is shown as the plugin’s own error, with its stack under Details.
  • slug turns “Crème brûlée” into creme-brulee: it separates letters from their accents (normalize('NFKD')), removes the accents (the combining marks U+0300 to U+036F), lowers the case, turns every run of other characters into one -, and trims dashes from the ends.
  • upper.schema is called with the step’s settings and its inputs (each with a name and its columns), before anything runs. It checks the column and says the output has the same columns as the input. This is what lets the step editor and the steps after it know the columns without running the step.
  • upper.compileSql returns one SELECT over the input by its name (input for the first input). SELECT * REPLACE (upper("Customer") AS "Customer") FROM input keeps every column and replaces one with its upper-case form. Because the step is SQL, it runs inside the engine’s own query, nothing crosses to the plugin’s process when the pipeline runs, and the step’s SQL tab shows exactly this query. The SQL may read only its inputs: the engine refuses a query that reads a file, calls a table function or names another table.
  • slugify.schema says the output is the input’s columns plus one text column named after into.
  • slugify.transform receives the input tables, each as { columns, rows } with one object per row, and returns the result as an array of row objects. An empty cell arrives as null and stays null; every other value gets a slug. The table crosses to the plugin’s process and back as JSON lines, every value as its exact text, so the other columns come back exactly as they went.

Installing it#

  1. Settings › Plugins › Install plugin….
  2. Give the path of the text-tools folder and choose Look at it. What it adds lists the two steps; What it asks to do is nothing beyond its own folder.
  3. Choose Install for This computer or This project, and Install. The toast says “Text tools 1.0.0 is installed”.

Using it#

Open a pipeline with a text column, such as Customer, and choose Add step › Plugin step. The step’s settings are JSON:

{ "pluginId": "example.text-tools", "step": "upper", "config": { "column": "Customer" } }

The preview shows Customer in upper case, and the step’s SQL tab shows the query compileSql returned. A second Plugin step with

{ "pluginId": "example.text-tools", "step": "slugify", "config": { "column": "Customer" } }

adds a column Slug. Name a column that does not exist and the step card says “There is no column called … in the table.” In the pipeline’s file the steps are stored as:

  - id: stp_upper00001
    kind: custom.plugin
    inputs: [stp_source0001]
    settings: { pluginId: example.text-tools, step: upper, config: { column: Customer } }

Anyone who opens the project on a computer without the plugin is told which plugin it needs; a copy in the project’s plugins/ folder runs only once someone on that computer confirms it.

Testing it#

The functions can be called directly, with no app and no process:

import assert from 'node:assert/strict';
import { test } from 'node:test';
import plugin from './index.mjs';

const ctx = { signal: new AbortController().signal, pluginDir: '.', dataDir: '.', tempDir: '.', log() {}, progress() {} };
const input = { name: 'input', columns: [{ name: 'Customer', type: 'text' }] };

test('upper is one SELECT over its input', () => {
  assert.equal(
    plugin.steps.upper.compileSql({ column: 'Customer' }, [input], ctx),
    'SELECT * REPLACE (upper("Customer") AS "Customer") FROM input',
  );
});

test('slugify keeps empty cells empty', () => {
  const table = { columns: input.columns, rows: [{ Customer: 'Crème brûlée' }, { Customer: null }] };
  const rows = plugin.steps.slugify.transform({ column: 'Customer', into: 'Slug' }, [table], ctx);
  assert.deepEqual(rows.map((r) => r.Slug), ['creme-brulee', null]);
});

test('a missing column is a plain sentence', () => {
  assert.throws(() => plugin.steps.upper.schema({ column: 'Nope' }, [input], ctx), /no column called Nope/);
});

Outside the app, @gridkiln/plugin-api must be resolvable for the import in index.mjs; see Testing a plugin for that and for testing through the same protocol the app uses. The engine’s own tests run this plugin through a real process: packages/engine/test/plugins/contributions.test.ts.

See also#