@nera-static/plugin-utils 1.0.4 → 1.1.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.
Files changed (3) hide show
  1. package/README.md +106 -12
  2. package/index.js +133 -5
  3. package/package.json +10 -4
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @nera/plugin-utils
1
+ # @nera-static/plugin-utils
2
2
 
3
3
  🛠 Utility helpers for developing plugins for the [Nera](https://github.com/seebaermichi/nera) static site generator.
4
4
 
@@ -14,35 +14,129 @@ npm install @nera-static/plugin-utils
14
14
 
15
15
  ## 📚 Features
16
16
 
17
- Currently includes:
17
+ ### Configuration Loading
18
18
 
19
- ### `getConfig(filePath: string): object`
19
+ #### `getConfig(filePath: string): object`
20
20
 
21
21
  Reads and parses a YAML config file, returning its contents as a JavaScript object.
22
22
 
23
- #### Example usage:
24
-
25
23
  ```js
26
- import { getConfig } from '@nera/plugin-utils'
24
+ import { getConfig } from '@nera-static/plugin-utils'
27
25
 
28
26
  const config = getConfig('./path/to/config.yaml')
29
27
  console.log(config.title)
30
28
  ```
31
29
 
32
- Returns `{}` if the file does not exist or is empty.
30
+ ### Template Publishing
31
+
32
+ #### `validateNeraProject(expectedPackageName?: string): boolean`
33
+
34
+ Validates if the current working directory is a valid Nera project by checking the `package.json`.
35
+
36
+ ```js
37
+ import { validateNeraProject } from '@nera-static/plugin-utils'
38
+
39
+ if (validateNeraProject()) {
40
+ console.log('Valid Nera project!')
41
+ }
42
+ ```
43
+
44
+ #### `publishTemplates(options): boolean`
45
+
46
+ Publishes specific template files from a plugin to a Nera project.
47
+
48
+ ```js
49
+ import { publishTemplates } from '@nera-static/plugin-utils'
50
+
51
+ const result = publishTemplates({
52
+ pluginName: 'plugin-my-awesome-plugin',
53
+ sourceDir: path.resolve(__dirname, '../views/'),
54
+ templateFiles: ['template.pug', 'another-template.pug'], // or single file as string
55
+ expectedPackageName: 'dummy', // optional, for testing
56
+ })
57
+ ```
58
+
59
+ #### `publishAllTemplates(options): boolean`
60
+
61
+ Publishes all `.pug` template files from a plugin's views directory to a Nera project.
62
+
63
+ ```js
64
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
65
+
66
+ const result = publishAllTemplates({
67
+ pluginName: 'plugin-my-awesome-plugin',
68
+ sourceDir: path.resolve(__dirname, '../views/'),
69
+ expectedPackageName: 'dummy', // optional, for testing
70
+ })
71
+ ```
72
+
73
+ ### Template Publishing CLI Integration
74
+
75
+ These functions are designed to be used in `bin/publish-template.js` scripts that can be executed via npm scripts:
76
+
77
+ ```js
78
+ #!/usr/bin/env node
79
+
80
+ import path from 'path'
81
+ import { fileURLToPath } from 'url'
82
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
83
+
84
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
85
+ const pluginName = 'plugin-my-awesome-plugin'
86
+ const sourceDir = path.resolve(__dirname, '../views/')
87
+
88
+ const result = publishAllTemplates({
89
+ pluginName,
90
+ sourceDir,
91
+ expectedPackageName: 'dummy', // for test-only override
92
+ })
93
+
94
+ process.exit(result ? 0 : 1)
95
+ ```
33
96
 
34
97
  ---
35
98
 
36
- ## 🧱 Use Case
99
+ ## 🧱 Use Cases
100
+
101
+ This package is intended for use inside Nera plugins to:
37
102
 
38
- This package is intended for use inside Nera plugins to simplify configuration loading from YAML files.
103
+ 1. **Load Configuration**: Simplify loading YAML configuration files
104
+ 2. **Publish Templates**: Standardize template publishing across plugins
105
+ 3. **Validate Projects**: Ensure commands run in valid Nera projects
39
106
 
40
- Example in a plugin:
107
+ ### Example Plugin Structure
108
+
109
+ ```js
110
+ // index.js - Main plugin file
111
+ import { getConfig } from '@nera-static/plugin-utils'
112
+
113
+ export function getAppData(app) {
114
+ const config = getConfig(`${__dirname}/config/my-plugin.yaml`)
115
+
116
+ return {
117
+ myPlugin: {
118
+ // ... plugin logic using config
119
+ },
120
+ }
121
+ }
122
+ ```
41
123
 
42
124
  ```js
43
- import { getConfig } from '@nera/plugin-utils'
125
+ // bin/publish-template.js - Template publishing script
126
+ #!/usr/bin/env node
127
+
128
+ import path from 'path'
129
+ import { fileURLToPath } from 'url'
130
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
131
+
132
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
133
+
134
+ const result = publishAllTemplates({
135
+ pluginName: 'plugin-my-awesome-plugin',
136
+ sourceDir: path.resolve(__dirname, '../views/')
137
+ })
44
138
 
45
- const config = getConfig(`${__dirname}/config/navigation.yaml`)
139
+ process.exit(result ? 0 : 1)
46
140
  ```
47
141
 
48
142
  ---
package/index.js CHANGED
@@ -1,10 +1,138 @@
1
1
  import fs from 'fs'
2
+ import path from 'path'
2
3
  import yaml from 'js-yaml'
3
4
 
4
5
  export function getConfig(filePath) {
5
- if (fs.existsSync(filePath)) {
6
- const content = fs.readFileSync(filePath, 'utf-8')
7
- return yaml.load(content) || {}
8
- }
9
- return {}
6
+ if (fs.existsSync(filePath)) {
7
+ const content = fs.readFileSync(filePath, 'utf-8')
8
+ return yaml.load(content) || {}
9
+ }
10
+ return {}
11
+ }
12
+
13
+ /**
14
+ * Validates if the current working directory is a valid Nera project
15
+ * @param {string} [expectedPackageName] - Override for testing purposes (defaults to 'dummy')
16
+ * @returns {boolean} - True if valid Nera project
17
+ */
18
+ export function validateNeraProject(expectedPackageName = 'dummy') {
19
+ const packageJsonPath = path.resolve(process.cwd(), 'package.json')
20
+
21
+ if (!fs.existsSync(packageJsonPath)) {
22
+ return false
23
+ }
24
+
25
+ try {
26
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
27
+ return pkg.name === expectedPackageName || pkg.name.startsWith('nera')
28
+ } catch (e) {
29
+ console.error(`❌ Error reading package.json: ${e.message}`)
30
+ return false
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Publishes template files from a plugin to a Nera project
36
+ * @param {Object} options - Configuration options
37
+ * @param {string} options.pluginName - Name of the plugin (e.g., 'plugin-popular-content')
38
+ * @param {string} options.sourceDir - Absolute path to the plugin's views directory
39
+ * @param {string|string[]} options.templateFiles - Single file or array of template files to copy
40
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
41
+ * @returns {boolean} - True if templates were published successfully
42
+ */
43
+ export function publishTemplates({
44
+ pluginName,
45
+ sourceDir,
46
+ templateFiles,
47
+ expectedPackageName
48
+ }) {
49
+ // Validate Nera project
50
+ if (!validateNeraProject(expectedPackageName)) {
51
+ console.error(
52
+ '❌ Please run this command from the root of your Nera project (where the plugin is installed).'
53
+ )
54
+ return false
55
+ }
56
+
57
+ const destinationDir = path.resolve(
58
+ process.cwd(),
59
+ `views/vendor/${pluginName}/`
60
+ )
61
+
62
+ // Check if destination already exists
63
+ if (fs.existsSync(destinationDir)) {
64
+ console.log(
65
+ `⚠️ Templates already exist at ${destinationDir}. Skipping.`
66
+ )
67
+ return true
68
+ }
69
+
70
+ // Ensure templateFiles is an array
71
+ const filesToCopy = Array.isArray(templateFiles)
72
+ ? templateFiles
73
+ : [templateFiles]
74
+
75
+ try {
76
+ // Create destination directory
77
+ fs.mkdirSync(destinationDir, { recursive: true })
78
+
79
+ // Copy each template file
80
+ filesToCopy.forEach((templateFile) => {
81
+ const sourcePath = path.resolve(sourceDir, templateFile)
82
+ const destPath = path.resolve(destinationDir, templateFile)
83
+
84
+ if (!fs.existsSync(sourcePath)) {
85
+ console.error(`❌ Source template not found: ${sourcePath}`)
86
+ return false
87
+ }
88
+
89
+ // Create subdirectories if needed
90
+ fs.mkdirSync(path.dirname(destPath), { recursive: true })
91
+
92
+ fs.copyFileSync(sourcePath, destPath)
93
+ console.log(`✅ Copied ${templateFile} to ${destPath}`)
94
+ })
95
+
96
+ console.log(`✅ Templates copied to: ${destinationDir}`)
97
+ return true
98
+ } catch (error) {
99
+ console.error(`❌ Failed to copy templates: ${error.message}`)
100
+ return false
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Publishes all .pug template files from a plugin's views directory
106
+ * @param {Object} options - Configuration options
107
+ * @param {string} options.pluginName - Name of the plugin (e.g., 'plugin-popular-content')
108
+ * @param {string} options.sourceDir - Absolute path to the plugin's views directory
109
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
110
+ * @returns {boolean} - True if templates were published successfully
111
+ */
112
+ export function publishAllTemplates({
113
+ pluginName,
114
+ sourceDir,
115
+ expectedPackageName
116
+ }) {
117
+ try {
118
+ // Get all .pug files from source directory
119
+ const pugFiles = fs
120
+ .readdirSync(sourceDir)
121
+ .filter((file) => file.endsWith('.pug'))
122
+
123
+ if (pugFiles.length === 0) {
124
+ console.log('⚠️ No .pug template files found to publish.')
125
+ return true
126
+ }
127
+
128
+ return publishTemplates({
129
+ pluginName,
130
+ sourceDir,
131
+ templateFiles: pugFiles,
132
+ expectedPackageName
133
+ })
134
+ } catch (error) {
135
+ console.error(`❌ Error reading source directory: ${error.message}`)
136
+ return false
137
+ }
10
138
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.0.4",
4
- "description": "Shared utility functions for Nera plugins (like config loading)",
3
+ "version": "1.1.0",
4
+ "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "repository": {
@@ -17,7 +17,8 @@
17
17
  "static-site-generator",
18
18
  "plugin",
19
19
  "utils",
20
- "yaml"
20
+ "yaml",
21
+ "templates"
21
22
  ],
22
23
  "author": "Michael Becker",
23
24
  "license": "MIT",
@@ -28,10 +29,15 @@
28
29
  "js-yaml": "^4.1.0"
29
30
  },
30
31
  "devDependencies": {
32
+ "eslint": "^9.17.0",
33
+ "husky": "^9.1.7",
31
34
  "vitest": "^3.2.4"
32
35
  },
33
36
  "scripts": {
34
- "test": "vitest"
37
+ "test": "vitest",
38
+ "lint": "eslint .",
39
+ "lint:fix": "eslint . --fix",
40
+ "prepare": "git config core.hooksPath .husky || true"
35
41
  },
36
42
  "exports": {
37
43
  ".": "./index.js"