@grafana/create-plugin 6.4.4 → 6.5.0-canary.2320.20231018478.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,17 +5,24 @@ This guide provides specific instructions for working with migrations and additi
5
5
  ## Agent Behavior
6
6
 
7
7
  - Refer to current migrations and additions typescript files found in @./additions/scripts and @./migrations/scripts
8
- - When creating a new migration add it to the exported migrations object in @./migrations/migrations.ts
9
8
  - Always refer to @./context.ts to know what methods are available on the context class
10
9
  - Always check for file existence using the @./context.ts class before attempting to do anything with it
11
10
  - Never write files with any 3rd party npm library. Use the context for all file operations
12
- - Always return the context for the next migration
11
+ - Always return the context for the next migration/addition
13
12
  - Test thoroughly using the provided utils in @./test-utils.ts where necessary
13
+ - Never attempt to read or write files outside the current working directory
14
+
15
+ ## Migrations
16
+
17
+ Migrations are automatically run during `create-plugin update` to keep plugins compatible with newer versions of the tooling. They are forced upon developers to ensure compatibility and are versioned based on the create-plugin version. Migrations primarily target configuration files or files that are scaffolded by create-plugin.
18
+
19
+ ### Migration Behavior
20
+
21
+ - When creating a new migration add it to the exported migrations object in @./migrations/migrations.ts
14
22
  - Each migration must be idempotent and must include a test case that uses the `.toBeIdempotent` custom matcher found in @../../vitest.setup.ts
15
23
  - Keep migrations focused on one task
16
- - Never attempt to read or write files outside the current working directory
17
24
 
18
- ## Naming Conventions
25
+ ### Migration Naming Conventions
19
26
 
20
27
  - Each migration lives under @./migrations/scripts
21
28
  - Migration filenames follow the format: `NNN-migration-title` where migration-title is, at the most, a three word summary of what the migration does and NNN is the next number in sequence based on the current file name in @./migrations/scripts
@@ -23,3 +30,16 @@ This guide provides specific instructions for working with migrations and additi
23
30
  - `NNN-migration-title.ts` - main migration logic
24
31
  - `NNN-migration-title.test.ts` - migration logic tests
25
32
  - Each migration should export a default function named "migrate"
33
+
34
+ ## Additions
35
+
36
+ Additions are optional features that developers choose to add via `create-plugin add`. They are not versioned and can be run at any time to enhance a plugin with new capabilities.
37
+
38
+ ### Addition Behavior
39
+
40
+ - Additions add new features or capabilities to a plugin (e.g., i18n support, testing frameworks, etc.)
41
+ - Each addition must be idempotent - it should be safe to run multiple times
42
+ - Always use defensive programming: check if features already exist before adding them
43
+ - Use `additionsDebug()` for logging to help with troubleshooting
44
+ - If the addition accepts user input, export a `schema` object using `valibot` for input validation
45
+ - Each addition should export a default function that takes `(context: Context, options?: T)` and returns `Context`
@@ -6,4 +6,9 @@ export default [
6
6
  description: 'Adds an example addition to the plugin',
7
7
  scriptPath: import.meta.resolve('./scripts/example-addition.js'),
8
8
  },
9
+ {
10
+ name: 'i18n',
11
+ description: 'Adds internationalization (i18n) support to the plugin',
12
+ scriptPath: import.meta.resolve('./scripts/i18n/index.js'),
13
+ },
9
14
  ] satisfies Codemod[];
@@ -0,0 +1,157 @@
1
+ # I18n Addition
2
+
3
+ Adds internationalization (i18n) support to a Grafana plugin.
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ npx @grafana/create-plugin add i18n --locales <locales>
9
+ ```
10
+
11
+ ## Required Flags
12
+
13
+ ### `--locales`
14
+
15
+ A comma-separated list of locale codes to support in your plugin.
16
+
17
+ **Format:** Locale codes must follow the `xx-XX` pattern (e.g., `en-US`, `es-ES`, `sv-SE`)
18
+
19
+ **Example:**
20
+
21
+ ```bash
22
+ npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
23
+ ```
24
+
25
+ ## What This Addition Does
26
+
27
+ This addition configures your plugin for internationalization by:
28
+
29
+ 1. **Updating `docker-compose.yaml`** - Adds the `localizationForPlugins` feature toggle to your local Grafana instance
30
+ 2. **Updating `src/plugin.json`** - Adds the `languages` array and updates `grafanaDependency`
31
+ 3. **Creating locale files** - Creates empty JSON files for each locale at `src/locales/{locale}/{pluginId}.json`
32
+ 4. **Adding dependencies** - Installs `@grafana/i18n` and optionally `semver` (for backward compatibility)
33
+ 5. **Updating ESLint config** - Adds i18n linting rules to catch untranslated strings
34
+ 6. **Initializing i18n in module.ts** - Adds `initPluginTranslations()` call to your plugin's entry point
35
+ 7. **Creating support files**:
36
+ - `i18next.config.ts` - Configuration for extracting translations
37
+ - `src/loadResources.ts` - (Only for Grafana < 12.1.0) Custom resource loader
38
+ 8. **Adding npm scripts** - Adds `i18n-extract` script to extract translations from your code
39
+
40
+ ## Backward Compatibility
41
+
42
+ The addition automatically detects your plugin's `grafanaDependency` version:
43
+
44
+ ### Grafana >= 12.1.0 (Modern)
45
+
46
+ - Sets `grafanaDependency` to `>=12.1.0`
47
+ - Grafana handles loading translations automatically
48
+ - Simple initialization: `await initPluginTranslations(pluginJson.id)`
49
+ - No `loadResources.ts` file needed
50
+ - No `semver` dependency needed
51
+
52
+ ### Grafana 11.0.0 - 12.0.x (Backward Compatible)
53
+
54
+ - Keeps or sets `grafanaDependency` to `>=11.0.0`
55
+ - Plugin handles loading translations
56
+ - Creates `src/loadResources.ts` for custom resource loading
57
+ - Adds runtime version check using `semver`
58
+ - Initialization with loaders: `await initPluginTranslations(pluginJson.id, loaders)`
59
+
60
+ ## Running Multiple Times (Idempotent)
61
+
62
+ This addition is **defensive** and can be run multiple times safely. Each operation checks if it's already been done:
63
+
64
+ ### Adding New Locales
65
+
66
+ You can run the command again with additional locales to add them:
67
+
68
+ ```bash
69
+ # First run
70
+ npx @grafana/create-plugin add i18n --locales en-US
71
+
72
+ # Later, add more locales
73
+ npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
74
+ ```
75
+
76
+ The addition will:
77
+
78
+ - ✅ Merge new locales into `plugin.json` without duplicates
79
+ - ✅ Create only the new locale files (won't overwrite existing ones)
80
+ - ✅ Skip updating files that already have i18n configured
81
+
82
+ ### What Won't Be Duplicated
83
+
84
+ - **Locale files**: Existing locale JSON files are never overwritten (preserves your translations)
85
+ - **Dependencies**: Won't re-add dependencies that already exist
86
+ - **ESLint config**: Won't duplicate the i18n plugin import or rules
87
+ - **Module initialization**: Won't add `initPluginTranslations` if it's already present
88
+ - **Support files**: Won't overwrite `i18next.config.ts` or `loadResources.ts` if they exist
89
+ - **npm scripts**: Won't overwrite the `i18n-extract` script if it exists
90
+ - **Docker feature toggle**: Won't duplicate the feature toggle
91
+
92
+ ## Files Created
93
+
94
+ ```
95
+ your-plugin/
96
+ ├── docker-compose.yaml # Modified: adds localizationForPlugins toggle
97
+ ├── src/
98
+ │ ├── plugin.json # Modified: adds languages array
99
+ │ ├── module.ts # Modified: adds i18n initialization
100
+ │ ├── loadResources.ts # Created: (Grafana 11.x only) resource loader
101
+ │ └── locales/
102
+ │ ├── en-US/
103
+ │ │ └── your-plugin-id.json # Created: empty translation file
104
+ │ ├── es-ES/
105
+ │ │ └── your-plugin-id.json # Created: empty translation file
106
+ │ └── sv-SE/
107
+ │ └── your-plugin-id.json # Created: empty translation file
108
+ ├── i18next.config.ts # Created: extraction config
109
+ ├── eslint.config.mjs # Modified: adds i18n linting rules
110
+ └── package.json # Modified: adds dependencies and scripts
111
+ ```
112
+
113
+ ## Dependencies Added
114
+
115
+ **Always:**
116
+
117
+ - `@grafana/i18n` (v12.2.2) - i18n utilities and types
118
+ - `i18next-cli` (dev) - Translation extraction tool
119
+
120
+ **For Grafana 11.x only:**
121
+
122
+ - `semver` - Runtime version checking
123
+ - `@types/semver` (dev) - TypeScript types for semver
124
+
125
+ ## Next Steps
126
+
127
+ After running this addition:
128
+
129
+ 1. **Extract translations**: Run `npm run i18n-extract` to scan your code for translatable strings
130
+ 2. **Add translations**: Fill in your locale JSON files with translated strings
131
+ 3. **Use in code**: Import and use the translation functions:
132
+
133
+ ```typescript
134
+ import { t, Trans } from '@grafana/i18n';
135
+
136
+ // Use t() for simple strings
137
+ const title = t('components.myComponent.title', 'Default Title');
138
+
139
+ // Use Trans for JSX
140
+ <Trans i18nKey="components.myComponent.description">
141
+ This is a description
142
+ </Trans>
143
+ ```
144
+
145
+ ## Debug Output
146
+
147
+ Enable debug logging to see what the addition is doing:
148
+
149
+ ```bash
150
+ DEBUG=create-plugin:additions npx @grafana/create-plugin add i18n --locales en-US,es-ES
151
+ ```
152
+
153
+ ## References
154
+
155
+ - [Grafana i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization)
156
+ - [Grafana 11.x i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization-grafana-11)
157
+ - [Available Languages](https://github.com/grafana/grafana/blob/main/packages/grafana-i18n/src/constants.ts)
@@ -0,0 +1,156 @@
1
+ import * as recast from 'recast';
2
+ import * as babelParser from 'recast/parsers/babel-ts.js';
3
+
4
+ import type { Context } from '../../../context.js';
5
+ import { additionsDebug } from '../../../utils.js';
6
+
7
+ const { builders } = recast.types;
8
+
9
+ export function addI18nInitialization(context: Context, needsBackwardCompatibility: boolean): void {
10
+ // Find module.ts or module.tsx
11
+ const moduleTsPath = context.doesFileExist('src/module.ts')
12
+ ? 'src/module.ts'
13
+ : context.doesFileExist('src/module.tsx')
14
+ ? 'src/module.tsx'
15
+ : null;
16
+
17
+ if (!moduleTsPath) {
18
+ additionsDebug('No module.ts or module.tsx found, skipping i18n initialization');
19
+ return;
20
+ }
21
+
22
+ const moduleContent = context.getFile(moduleTsPath);
23
+ if (!moduleContent) {
24
+ return;
25
+ }
26
+
27
+ // Defensive: check if i18n is already initialized
28
+ if (moduleContent.includes('initPluginTranslations')) {
29
+ additionsDebug('i18n already initialized in module file');
30
+ return;
31
+ }
32
+
33
+ try {
34
+ const ast = recast.parse(moduleContent, {
35
+ parser: babelParser,
36
+ });
37
+
38
+ const imports = [];
39
+
40
+ // Add necessary imports based on backward compatibility
41
+ imports.push(
42
+ builders.importDeclaration(
43
+ [builders.importSpecifier(builders.identifier('initPluginTranslations'))],
44
+ builders.literal('@grafana/i18n')
45
+ )
46
+ );
47
+
48
+ imports.push(
49
+ builders.importDeclaration(
50
+ [builders.importDefaultSpecifier(builders.identifier('pluginJson'))],
51
+ builders.literal('plugin.json')
52
+ )
53
+ );
54
+
55
+ if (needsBackwardCompatibility) {
56
+ imports.push(
57
+ builders.importDeclaration(
58
+ [builders.importSpecifier(builders.identifier('config'))],
59
+ builders.literal('@grafana/runtime')
60
+ )
61
+ );
62
+ imports.push(
63
+ builders.importDeclaration(
64
+ [builders.importDefaultSpecifier(builders.identifier('semver'))],
65
+ builders.literal('semver')
66
+ )
67
+ );
68
+ imports.push(
69
+ builders.importDeclaration(
70
+ [builders.importSpecifier(builders.identifier('loadResources'))],
71
+ builders.literal('./loadResources')
72
+ )
73
+ );
74
+ }
75
+
76
+ // Add imports after the first import statement
77
+ const firstImportIndex = ast.program.body.findIndex((node: any) => node.type === 'ImportDeclaration');
78
+ if (firstImportIndex !== -1) {
79
+ ast.program.body.splice(firstImportIndex + 1, 0, ...imports);
80
+ } else {
81
+ ast.program.body.unshift(...imports);
82
+ }
83
+
84
+ // Add i18n initialization code
85
+ const i18nInitCode = needsBackwardCompatibility
86
+ ? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
87
+ // In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
88
+ const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : [];
89
+
90
+ await initPluginTranslations(pluginJson.id, loaders);`
91
+ : `await initPluginTranslations(pluginJson.id);`;
92
+
93
+ // Parse the initialization code and insert it at the top level (after imports)
94
+ const initAst = recast.parse(i18nInitCode, {
95
+ parser: babelParser,
96
+ });
97
+
98
+ // Find the last import index
99
+ const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
100
+ if (lastImportIndex !== -1) {
101
+ ast.program.body.splice(lastImportIndex + 1, 0, ...initAst.program.body);
102
+ } else {
103
+ ast.program.body.unshift(...initAst.program.body);
104
+ }
105
+
106
+ const output = recast.print(ast, {
107
+ tabWidth: 2,
108
+ trailingComma: true,
109
+ lineTerminator: '\n',
110
+ }).code;
111
+
112
+ context.updateFile(moduleTsPath, output);
113
+ additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
114
+ } catch (error) {
115
+ additionsDebug('Error updating module file:', error);
116
+ }
117
+ }
118
+
119
+ export function createLoadResourcesFile(context: Context): void {
120
+ const loadResourcesPath = 'src/loadResources.ts';
121
+
122
+ // Defensive: skip if already exists
123
+ if (context.doesFileExist(loadResourcesPath)) {
124
+ additionsDebug('loadResources.ts already exists, skipping');
125
+ return;
126
+ }
127
+
128
+ const pluginJsonRaw = context.getFile('src/plugin.json');
129
+ if (!pluginJsonRaw) {
130
+ additionsDebug('Cannot create loadResources.ts without plugin.json');
131
+ return;
132
+ }
133
+
134
+ const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
135
+ import pluginJson from 'plugin.json';
136
+
137
+ const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
138
+ acc[lang.code] = async () => await import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
139
+ return acc;
140
+ }, {});
141
+
142
+ export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
143
+ try {
144
+ const translation = await resources[resolvedLanguage]();
145
+ return translation.default;
146
+ } catch (error) {
147
+ // This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
148
+ console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
149
+ return {};
150
+ }
151
+ };
152
+ `;
153
+
154
+ context.addFile(loadResourcesPath, loadResourcesContent);
155
+ additionsDebug('Created src/loadResources.ts for backward compatibility');
156
+ }