@grafana/create-plugin 6.5.0-canary.2320.20268376971.0 → 6.5.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.
- package/CHANGELOG.md +17 -0
- package/dist/codemods/additions/additions.js +3 -3
- package/dist/codemods/utils.js +2 -2
- package/package.json +2 -2
- package/src/codemods/AGENTS.md +4 -24
- package/src/codemods/additions/additions.ts +3 -3
- package/templates/panel/src/plugin.json +1 -1
- package/dist/codemods/additions/scripts/i18n/code-generation.js +0 -122
- package/dist/codemods/additions/scripts/i18n/config-updates.js +0 -250
- package/dist/codemods/additions/scripts/i18n/index.js +0 -64
- package/dist/codemods/additions/scripts/i18n/tooling.js +0 -121
- package/dist/codemods/additions/scripts/i18n/utils.js +0 -83
- package/src/codemods/additions/scripts/i18n/README.md +0 -161
- package/src/codemods/additions/scripts/i18n/code-generation.ts +0 -158
- package/src/codemods/additions/scripts/i18n/config-updates.test.ts +0 -209
- package/src/codemods/additions/scripts/i18n/config-updates.ts +0 -335
- package/src/codemods/additions/scripts/i18n/index.test.ts +0 -674
- package/src/codemods/additions/scripts/i18n/index.ts +0 -102
- package/src/codemods/additions/scripts/i18n/tooling.test.ts +0 -80
- package/src/codemods/additions/scripts/i18n/tooling.ts +0 -150
- package/src/codemods/additions/scripts/i18n/utils.test.ts +0 -133
- package/src/codemods/additions/scripts/i18n/utils.ts +0 -106
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
import * as recast from 'recast';
|
|
2
|
-
import * as babelParser from 'recast/parsers/babel-ts.js';
|
|
3
|
-
import { addDependenciesToPackageJson, additionsDebug } from '../../../utils.js';
|
|
4
|
-
|
|
5
|
-
const { builders } = recast.types;
|
|
6
|
-
function addI18nDependency(context) {
|
|
7
|
-
addDependenciesToPackageJson(context, { "@grafana/i18n": "^12.2.2" }, {});
|
|
8
|
-
additionsDebug("Added @grafana/i18n dependency version ^12.2.2");
|
|
9
|
-
}
|
|
10
|
-
function addSemverDependency(context) {
|
|
11
|
-
addDependenciesToPackageJson(context, { semver: "^7.6.0" }, { "@types/semver": "^7.5.0" });
|
|
12
|
-
additionsDebug("Added semver dependency");
|
|
13
|
-
}
|
|
14
|
-
function addI18nextCli(context) {
|
|
15
|
-
addDependenciesToPackageJson(context, {}, { "i18next-cli": "^1.1.1" });
|
|
16
|
-
const packageJsonRaw = context.getFile("package.json");
|
|
17
|
-
if (!packageJsonRaw) {
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
try {
|
|
21
|
-
const packageJson = JSON.parse(packageJsonRaw);
|
|
22
|
-
if (!packageJson.scripts) {
|
|
23
|
-
packageJson.scripts = {};
|
|
24
|
-
}
|
|
25
|
-
if (!packageJson.scripts["i18n-extract"]) {
|
|
26
|
-
packageJson.scripts["i18n-extract"] = "i18next-cli extract --sync-primary";
|
|
27
|
-
context.updateFile("package.json", JSON.stringify(packageJson, null, 2));
|
|
28
|
-
additionsDebug("Added i18n-extract script to package.json");
|
|
29
|
-
} else {
|
|
30
|
-
additionsDebug("i18n-extract script already exists, skipping");
|
|
31
|
-
}
|
|
32
|
-
} catch (error) {
|
|
33
|
-
additionsDebug("Error adding i18n-extract script:", error);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
function updateEslintConfig(context) {
|
|
37
|
-
if (!context.doesFileExist("eslint.config.mjs")) {
|
|
38
|
-
additionsDebug("eslint.config.mjs not found, skipping");
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
const eslintConfigRaw = context.getFile("eslint.config.mjs");
|
|
42
|
-
if (!eslintConfigRaw) {
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
if (eslintConfigRaw.includes("@grafana/i18n/eslint-plugin")) {
|
|
46
|
-
additionsDebug("ESLint i18n rule already configured");
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
try {
|
|
50
|
-
const ast = recast.parse(eslintConfigRaw, {
|
|
51
|
-
parser: babelParser
|
|
52
|
-
});
|
|
53
|
-
const imports = ast.program.body.filter((node) => node.type === "ImportDeclaration");
|
|
54
|
-
const lastImport = imports[imports.length - 1];
|
|
55
|
-
const pluginImport = builders.importDeclaration(
|
|
56
|
-
[builders.importDefaultSpecifier(builders.identifier("grafanaI18nPlugin"))],
|
|
57
|
-
builders.literal("@grafana/i18n/eslint-plugin")
|
|
58
|
-
);
|
|
59
|
-
if (lastImport) {
|
|
60
|
-
const lastImportIndex = ast.program.body.indexOf(lastImport);
|
|
61
|
-
ast.program.body.splice(lastImportIndex + 1, 0, pluginImport);
|
|
62
|
-
} else {
|
|
63
|
-
ast.program.body.unshift(pluginImport);
|
|
64
|
-
}
|
|
65
|
-
recast.visit(ast, {
|
|
66
|
-
visitCallExpression(path) {
|
|
67
|
-
if (path.node.callee.name === "defineConfig" && path.node.arguments[0]?.type === "ArrayExpression") {
|
|
68
|
-
const configArray = path.node.arguments[0];
|
|
69
|
-
const i18nConfig = builders.objectExpression([
|
|
70
|
-
builders.property("init", builders.identifier("name"), builders.literal("grafana/i18n-rules")),
|
|
71
|
-
builders.property(
|
|
72
|
-
"init",
|
|
73
|
-
builders.identifier("plugins"),
|
|
74
|
-
builders.objectExpression([
|
|
75
|
-
builders.property("init", builders.literal("@grafana/i18n"), builders.identifier("grafanaI18nPlugin"))
|
|
76
|
-
])
|
|
77
|
-
),
|
|
78
|
-
builders.property(
|
|
79
|
-
"init",
|
|
80
|
-
builders.identifier("rules"),
|
|
81
|
-
builders.objectExpression([
|
|
82
|
-
builders.property(
|
|
83
|
-
"init",
|
|
84
|
-
builders.literal("@grafana/i18n/no-untranslated-strings"),
|
|
85
|
-
builders.arrayExpression([
|
|
86
|
-
builders.literal("error"),
|
|
87
|
-
builders.objectExpression([
|
|
88
|
-
builders.property(
|
|
89
|
-
"init",
|
|
90
|
-
builders.identifier("calleesToIgnore"),
|
|
91
|
-
builders.arrayExpression([builders.literal("^css$"), builders.literal("use[A-Z].*")])
|
|
92
|
-
)
|
|
93
|
-
])
|
|
94
|
-
])
|
|
95
|
-
),
|
|
96
|
-
builders.property(
|
|
97
|
-
"init",
|
|
98
|
-
builders.literal("@grafana/i18n/no-translation-top-level"),
|
|
99
|
-
builders.literal("error")
|
|
100
|
-
)
|
|
101
|
-
])
|
|
102
|
-
)
|
|
103
|
-
]);
|
|
104
|
-
configArray.elements.push(i18nConfig);
|
|
105
|
-
}
|
|
106
|
-
this.traverse(path);
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
const output = recast.print(ast, {
|
|
110
|
-
tabWidth: 2,
|
|
111
|
-
trailingComma: true,
|
|
112
|
-
lineTerminator: "\n"
|
|
113
|
-
}).code;
|
|
114
|
-
context.updateFile("eslint.config.mjs", output);
|
|
115
|
-
additionsDebug("Updated eslint.config.mjs with i18n linting rules");
|
|
116
|
-
} catch (error) {
|
|
117
|
-
additionsDebug("Error updating eslint.config.mjs:", error);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export { addI18nDependency, addI18nextCli, addSemverDependency, updateEslintConfig };
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import { coerce, gte } from 'semver';
|
|
2
|
-
import { additionsDebug } from '../../../utils.js';
|
|
3
|
-
|
|
4
|
-
function checkReactVersion(context) {
|
|
5
|
-
const packageJsonRaw = context.getFile("package.json");
|
|
6
|
-
if (!packageJsonRaw) {
|
|
7
|
-
return;
|
|
8
|
-
}
|
|
9
|
-
try {
|
|
10
|
-
const packageJson = JSON.parse(packageJsonRaw);
|
|
11
|
-
const reactVersion = packageJson.dependencies?.react || packageJson.devDependencies?.react || packageJson.peerDependencies?.react;
|
|
12
|
-
if (reactVersion) {
|
|
13
|
-
const reactVersionStr = reactVersion.replace(/[^0-9.]/g, "");
|
|
14
|
-
const reactVersionCoerced = coerce(reactVersionStr);
|
|
15
|
-
if (reactVersionCoerced && !gte(reactVersionCoerced, "18.0.0")) {
|
|
16
|
-
throw new Error(
|
|
17
|
-
`@grafana/i18n requires React 18 or higher. Your plugin is using React ${reactVersion}.
|
|
18
|
-
|
|
19
|
-
Please upgrade to React 18+ to use i18n support.
|
|
20
|
-
Update your package.json to use "react": "^18.3.0" and "react-dom": "^18.3.0".`
|
|
21
|
-
);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
} catch (error) {
|
|
25
|
-
if (error instanceof Error && error.message.includes("@grafana/i18n requires React")) {
|
|
26
|
-
throw error;
|
|
27
|
-
}
|
|
28
|
-
additionsDebug("Error checking React version:", error);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
function checkNeedsBackwardCompatibility(context) {
|
|
32
|
-
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
33
|
-
if (!pluginJsonRaw) {
|
|
34
|
-
return true;
|
|
35
|
-
}
|
|
36
|
-
try {
|
|
37
|
-
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
38
|
-
const currentGrafanaDep = pluginJson.dependencies?.grafanaDependency;
|
|
39
|
-
if (!currentGrafanaDep) {
|
|
40
|
-
additionsDebug(
|
|
41
|
-
"Warning: grafanaDependency is missing from plugin.json. Assuming backward compatibility mode is needed."
|
|
42
|
-
);
|
|
43
|
-
return true;
|
|
44
|
-
}
|
|
45
|
-
const minVersion = coerce("12.1.0");
|
|
46
|
-
const currentVersion = coerce(currentGrafanaDep.replace(/^[><=]+/, ""));
|
|
47
|
-
if (currentVersion && minVersion && gte(currentVersion, minVersion)) {
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
return true;
|
|
51
|
-
} catch (error) {
|
|
52
|
-
additionsDebug("Error checking backward compatibility:", error);
|
|
53
|
-
return true;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function createLocaleFiles(context, locales) {
|
|
57
|
-
const pluginJsonRaw = context.getFile("src/plugin.json");
|
|
58
|
-
if (!pluginJsonRaw) {
|
|
59
|
-
additionsDebug("Cannot create locale files without plugin.json");
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
try {
|
|
63
|
-
const pluginJson = JSON.parse(pluginJsonRaw);
|
|
64
|
-
const pluginId = pluginJson.id;
|
|
65
|
-
if (!pluginId) {
|
|
66
|
-
additionsDebug("No plugin ID found in plugin.json");
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
for (const locale of locales) {
|
|
70
|
-
const localePath = `src/locales/${locale}/${pluginId}.json`;
|
|
71
|
-
if (!context.doesFileExist(localePath)) {
|
|
72
|
-
context.addFile(localePath, JSON.stringify({}, null, 2));
|
|
73
|
-
additionsDebug(`Created ${localePath}`);
|
|
74
|
-
} else {
|
|
75
|
-
additionsDebug(`${localePath} already exists, skipping`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
} catch (error) {
|
|
79
|
-
additionsDebug("Error creating locale files:", error);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export { checkNeedsBackwardCompatibility, checkReactVersion, createLocaleFiles };
|
|
@@ -1,161 +0,0 @@
|
|
|
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
|
-
## Requirements
|
|
12
|
-
|
|
13
|
-
- **Grafana >= 11.0.0**: i18n is not supported for Grafana versions prior to 11.0.0. If your plugin's `grafanaDependency` is set to a version < 11.0.0, the script will automatically update it to `>=11.0.0` (it will not exit with an error).
|
|
14
|
-
- **React >= 18**: The `@grafana/i18n` package requires React 18 or higher. If your plugin uses React < 18, the script will exit with an error and prompt you to upgrade.
|
|
15
|
-
|
|
16
|
-
## Required Flags
|
|
17
|
-
|
|
18
|
-
### `--locales`
|
|
19
|
-
|
|
20
|
-
A comma-separated list of locale codes to support in your plugin.
|
|
21
|
-
|
|
22
|
-
**Format:** Locale codes must follow the `xx-XX` pattern (e.g., `en-US`, `es-ES`, `sv-SE`)
|
|
23
|
-
|
|
24
|
-
**Example:**
|
|
25
|
-
|
|
26
|
-
```bash
|
|
27
|
-
npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
## What This Addition Does
|
|
31
|
-
|
|
32
|
-
**Important:** This script sets up the infrastructure and configuration needed for translations. After running this script, you'll need to:
|
|
33
|
-
|
|
34
|
-
1. Mark up your code with translation functions (`t()` and `<Trans>`)
|
|
35
|
-
2. Run `npm run i18n-extract` to extract translatable strings
|
|
36
|
-
3. Fill in the locale JSON files with translated strings
|
|
37
|
-
|
|
38
|
-
This addition configures your plugin for internationalization by:
|
|
39
|
-
|
|
40
|
-
1. **Updating `docker-compose.yaml`** - Adds the `localizationForPlugins` feature toggle to your local Grafana instance
|
|
41
|
-
2. **Updating `src/plugin.json`** - Adds the `languages` array and updates `grafanaDependency`
|
|
42
|
-
3. **Creating locale files** - Creates empty JSON files for each locale at `src/locales/{locale}/{pluginId}.json`
|
|
43
|
-
4. **Adding dependencies** - Installs `@grafana/i18n` and optionally `semver` (for backward compatibility)
|
|
44
|
-
5. **Updating ESLint config** - Adds i18n linting rules to catch untranslated strings
|
|
45
|
-
6. **Initializing i18n in module.ts** - Adds `initPluginTranslations()` call to your plugin's entry point
|
|
46
|
-
7. **Creating support files**:
|
|
47
|
-
- `i18next.config.ts` - Configuration for extracting translations
|
|
48
|
-
- `src/loadResources.ts` - (Only for Grafana < 12.1.0) Custom resource loader
|
|
49
|
-
8. **Adding npm scripts** - Adds `i18n-extract` script to extract translations from your code
|
|
50
|
-
|
|
51
|
-
## Backward Compatibility
|
|
52
|
-
|
|
53
|
-
**Note:** i18n is not supported for Grafana versions prior to 11.0.0.
|
|
54
|
-
|
|
55
|
-
The addition automatically detects your plugin's `grafanaDependency` version:
|
|
56
|
-
|
|
57
|
-
### Grafana >= 12.1.0
|
|
58
|
-
|
|
59
|
-
- Sets `grafanaDependency` to `>=12.1.0`
|
|
60
|
-
- Grafana handles loading translations automatically
|
|
61
|
-
- Simple initialization: `await initPluginTranslations(pluginJson.id)`
|
|
62
|
-
- No `loadResources.ts` file needed
|
|
63
|
-
- No `semver` dependency needed
|
|
64
|
-
|
|
65
|
-
### Grafana 11.0.0 - 12.0.x
|
|
66
|
-
|
|
67
|
-
- Keeps or sets `grafanaDependency` to `>=11.0.0`
|
|
68
|
-
- Plugin handles loading translations
|
|
69
|
-
- Creates `src/loadResources.ts` for custom resource loading
|
|
70
|
-
- Adds runtime version check using `semver`
|
|
71
|
-
- Initialization with loaders: `await initPluginTranslations(pluginJson.id, loaders)`
|
|
72
|
-
|
|
73
|
-
## Running Multiple Times
|
|
74
|
-
|
|
75
|
-
This addition can be run multiple times safely. It uses defensive programming to check if configurations already exist before adding them, preventing duplicates and overwrites:
|
|
76
|
-
|
|
77
|
-
### Adding New Locales
|
|
78
|
-
|
|
79
|
-
You can run the command again with additional locales to add them:
|
|
80
|
-
|
|
81
|
-
```bash
|
|
82
|
-
# First run
|
|
83
|
-
npx @grafana/create-plugin add i18n --locales en-US
|
|
84
|
-
|
|
85
|
-
# Later, add more locales
|
|
86
|
-
npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
The addition will:
|
|
90
|
-
|
|
91
|
-
- Merge new locales into `plugin.json` without duplicates
|
|
92
|
-
- Create only the new locale files (won't overwrite existing ones)
|
|
93
|
-
- Skip updating files that already have i18n configured
|
|
94
|
-
|
|
95
|
-
## Files Created
|
|
96
|
-
|
|
97
|
-
```
|
|
98
|
-
your-plugin/
|
|
99
|
-
├── docker-compose.yaml # Modified: adds localizationForPlugins toggle
|
|
100
|
-
├── src/
|
|
101
|
-
│ ├── plugin.json # Modified: adds languages array
|
|
102
|
-
│ ├── module.ts # Modified: adds i18n initialization
|
|
103
|
-
│ ├── loadResources.ts # Created: (Grafana 11.x only) resource loader
|
|
104
|
-
│ └── locales/
|
|
105
|
-
│ ├── en-US/
|
|
106
|
-
│ │ └── your-plugin-id.json # Created: empty translation file
|
|
107
|
-
│ ├── es-ES/
|
|
108
|
-
│ │ └── your-plugin-id.json # Created: empty translation file
|
|
109
|
-
│ └── sv-SE/
|
|
110
|
-
│ └── your-plugin-id.json # Created: empty translation file
|
|
111
|
-
├── i18next.config.ts # Created: extraction config
|
|
112
|
-
├── eslint.config.mjs # Modified: adds i18n linting rules
|
|
113
|
-
└── package.json # Modified: adds dependencies and scripts
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
## Dependencies Added
|
|
117
|
-
|
|
118
|
-
**Always:**
|
|
119
|
-
|
|
120
|
-
- `@grafana/i18n` (v12.2.2) - i18n utilities and types
|
|
121
|
-
- `i18next-cli` (dev) - Translation extraction tool
|
|
122
|
-
|
|
123
|
-
**For Grafana 11.x only:**
|
|
124
|
-
|
|
125
|
-
- `semver` - Runtime version checking
|
|
126
|
-
- `@types/semver` (dev) - TypeScript types for semver
|
|
127
|
-
|
|
128
|
-
## Next Steps
|
|
129
|
-
|
|
130
|
-
After running this addition:
|
|
131
|
-
|
|
132
|
-
1. **Use in code**: Import and use the translation functions to mark up your code:
|
|
133
|
-
|
|
134
|
-
```typescript
|
|
135
|
-
import { t, Trans } from '@grafana/i18n';
|
|
136
|
-
|
|
137
|
-
// Use t() for simple strings
|
|
138
|
-
const title = t('components.myComponent.title', 'Default Title');
|
|
139
|
-
|
|
140
|
-
// Use Trans for JSX
|
|
141
|
-
<Trans i18nKey="components.myComponent.description">
|
|
142
|
-
This is a description
|
|
143
|
-
</Trans>
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
2. **Extract translations**: Run `npm run i18n-extract` to scan your code for translatable strings
|
|
147
|
-
3. **Add translations**: Fill in your locale JSON files with translated strings
|
|
148
|
-
|
|
149
|
-
## Debug Output
|
|
150
|
-
|
|
151
|
-
Enable debug logging to see what the addition is doing:
|
|
152
|
-
|
|
153
|
-
```bash
|
|
154
|
-
DEBUG=create-plugin:additions npx @grafana/create-plugin add i18n --locales en-US,es-ES
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
## References
|
|
158
|
-
|
|
159
|
-
- [Grafana i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization)
|
|
160
|
-
- [Grafana 11.x i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization-grafana-11)
|
|
161
|
-
- [Available Languages](https://github.com/grafana/grafana/blob/main/packages/grafana-i18n/src/constants.ts)
|
|
@@ -1,158 +0,0 @@
|
|
|
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
|
-
// Find the last import index (use consistent approach for both imports and initialization)
|
|
77
|
-
const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
|
|
78
|
-
|
|
79
|
-
// Add imports after the last import statement
|
|
80
|
-
if (lastImportIndex !== -1) {
|
|
81
|
-
ast.program.body.splice(lastImportIndex + 1, 0, ...imports);
|
|
82
|
-
} else {
|
|
83
|
-
ast.program.body.unshift(...imports);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Add i18n initialization code
|
|
87
|
-
const i18nInitCode = needsBackwardCompatibility
|
|
88
|
-
? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources
|
|
89
|
-
// In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources
|
|
90
|
-
const loaders = semver.lt(config?.buildInfo?.version || '0.0.0', '12.1.0') ? [loadResources] : [];
|
|
91
|
-
|
|
92
|
-
await initPluginTranslations(pluginJson.id, loaders);`
|
|
93
|
-
: `await initPluginTranslations(pluginJson.id);`;
|
|
94
|
-
|
|
95
|
-
// Parse the initialization code and insert it at the top level (after imports)
|
|
96
|
-
const initAst = recast.parse(i18nInitCode, {
|
|
97
|
-
parser: babelParser,
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
// Find the last import index again (after adding new imports)
|
|
101
|
-
const finalLastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration');
|
|
102
|
-
if (finalLastImportIndex !== -1) {
|
|
103
|
-
ast.program.body.splice(finalLastImportIndex + 1, 0, ...initAst.program.body);
|
|
104
|
-
} else {
|
|
105
|
-
ast.program.body.unshift(...initAst.program.body);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
const output = recast.print(ast, {
|
|
109
|
-
tabWidth: 2,
|
|
110
|
-
trailingComma: true,
|
|
111
|
-
lineTerminator: '\n',
|
|
112
|
-
}).code;
|
|
113
|
-
|
|
114
|
-
context.updateFile(moduleTsPath, output);
|
|
115
|
-
additionsDebug(`Updated ${moduleTsPath} with i18n initialization`);
|
|
116
|
-
} catch (error) {
|
|
117
|
-
additionsDebug('Error updating module file:', error);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function createLoadResourcesFile(context: Context): void {
|
|
122
|
-
const loadResourcesPath = 'src/loadResources.ts';
|
|
123
|
-
|
|
124
|
-
// Defensive: skip if already exists
|
|
125
|
-
if (context.doesFileExist(loadResourcesPath)) {
|
|
126
|
-
additionsDebug('loadResources.ts already exists, skipping');
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const pluginJsonRaw = context.getFile('src/plugin.json');
|
|
131
|
-
if (!pluginJsonRaw) {
|
|
132
|
-
additionsDebug('Cannot create loadResources.ts without plugin.json');
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n';
|
|
137
|
-
import pluginJson from 'plugin.json';
|
|
138
|
-
|
|
139
|
-
const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => {
|
|
140
|
-
acc[lang.code] = () => import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`);
|
|
141
|
-
return acc;
|
|
142
|
-
}, {});
|
|
143
|
-
|
|
144
|
-
export const loadResources: ResourceLoader = async (resolvedLanguage: string) => {
|
|
145
|
-
try {
|
|
146
|
-
const translation = await resources[resolvedLanguage]();
|
|
147
|
-
return translation.default;
|
|
148
|
-
} catch (error) {
|
|
149
|
-
// This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin
|
|
150
|
-
console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error);
|
|
151
|
-
return {};
|
|
152
|
-
}
|
|
153
|
-
};
|
|
154
|
-
`;
|
|
155
|
-
|
|
156
|
-
context.addFile(loadResourcesPath, loadResourcesContent);
|
|
157
|
-
additionsDebug('Created src/loadResources.ts for backward compatibility');
|
|
158
|
-
}
|