lapikit 0.2.0 → 0.2.2

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.
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { terminal } from './helper.js';
5
+ import presets from './presets.js';
6
+
7
+ async function findReferenceFile(projectPath) {
8
+ const routesPath = path.join(projectPath, 'src', 'routes');
9
+
10
+ try {
11
+ await fs.access(routesPath);
12
+ } catch {
13
+ terminal('error', `Lapikit cannot find the routes/ directory.`);
14
+ // throw new Error('Lapikit cannot find the routes/ directory.');
15
+ }
16
+
17
+ const layoutFile = path.join(routesPath, '+layout.svelte');
18
+ try {
19
+ await fs.access(layoutFile);
20
+ return layoutFile;
21
+ } catch {
22
+ // +layout.svelte not found in routes/
23
+ }
24
+
25
+ const pageFile = path.join(routesPath, '+page.svelte');
26
+ try {
27
+ await fs.access(pageFile);
28
+ return pageFile;
29
+ } catch {
30
+ // +page.svelte not found in routes/
31
+ }
32
+
33
+ try {
34
+ const entries = await fs.readdir(routesPath, { withFileTypes: true });
35
+ const subDirectories = entries.filter((entry) => entry.isDirectory());
36
+
37
+ for (const dir of subDirectories) {
38
+ const subDirPath = path.join(routesPath, dir.name);
39
+
40
+ const subLayoutFile = path.join(subDirPath, '+layout.svelte');
41
+ try {
42
+ await fs.access(subLayoutFile);
43
+ return subLayoutFile;
44
+ } catch {
45
+ // +layout.svelte not found in subdirectory
46
+ }
47
+
48
+ const subPageFile = path.join(subDirPath, '+page.svelte');
49
+ try {
50
+ await fs.access(subPageFile);
51
+ return subPageFile;
52
+ } catch {
53
+ // +page.svelte not found in subdirectory
54
+ }
55
+ }
56
+ } catch {
57
+ // Error reading routes directory
58
+ }
59
+
60
+ throw new Error('Not found +layout or +page main on your project.');
61
+ }
62
+
63
+ async function addImportToReferenceFile(targetFile, referenceFile) {
64
+ try {
65
+ const content = await fs.readFile(referenceFile, 'utf-8');
66
+ const relativePath = path.relative(path.dirname(referenceFile), targetFile);
67
+ const importStatement = `import "${relativePath.startsWith('.') ? relativePath : './' + relativePath}";\n`;
68
+
69
+ if (content.includes(`import "${relativePath}"`)) {
70
+ terminal('info', `Import statement already exists in ${referenceFile}`);
71
+ return;
72
+ }
73
+
74
+ const lines = content.split('\n');
75
+ let insertIndex = -1;
76
+
77
+ for (let i = 0; i < lines.length; i++) {
78
+ const line = lines[i].trim();
79
+ if (line.startsWith('<script>') || line.startsWith('<script lang="ts">')) {
80
+ insertIndex = i + 1;
81
+ break;
82
+ }
83
+ }
84
+
85
+ if (insertIndex === -1) {
86
+ throw new Error(`No found balise <script> ou <script lang="ts"> ${referenceFile}`);
87
+ }
88
+
89
+ let finalInsertIndex = insertIndex;
90
+ for (let i = insertIndex; i < lines.length; i++) {
91
+ const line = lines[i].trim();
92
+
93
+ if (line === '</script>') {
94
+ break;
95
+ }
96
+
97
+ if (line === '' || line.startsWith('import ') || line.startsWith('//')) {
98
+ finalInsertIndex = i + 1;
99
+ } else {
100
+ break;
101
+ }
102
+ }
103
+
104
+ lines.splice(finalInsertIndex, 0, `\t${importStatement.trim()}`);
105
+ const newContent = lines.join('\n');
106
+
107
+ await fs.writeFile(referenceFile, newContent);
108
+ terminal('info', `Import has been added to ${referenceFile}`);
109
+ } catch (error) {
110
+ terminal('error', `Error adding import: ${error.message}`);
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ async function findViteConfigFile(projectPath, typescript) {
116
+ const ext = typescript ? 'ts' : 'js';
117
+ const viteConfigFile = path.join(projectPath, `vite.config.${ext}`);
118
+
119
+ try {
120
+ await fs.access(viteConfigFile);
121
+ return viteConfigFile;
122
+ } catch {
123
+ // Try the other extension if the preferred one doesn't exist
124
+ const alternativeExt = typescript ? 'js' : 'ts';
125
+ const alternativeFile = path.join(projectPath, `vite.config.${alternativeExt}`);
126
+
127
+ try {
128
+ await fs.access(alternativeFile);
129
+ return alternativeFile;
130
+ } catch {
131
+ throw new Error(`No vite.config.js or vite.config.ts file found in ${projectPath}`);
132
+ }
133
+ }
134
+ }
135
+
136
+ async function addLapikitToViteConfig(viteConfigFile) {
137
+ try {
138
+ const content = await fs.readFile(viteConfigFile, 'utf-8');
139
+ const lapikitImport = `import { lapikit } from 'lapikit/vite';`;
140
+
141
+ // Check if lapikit import already exists
142
+ if (content.includes(lapikitImport) || content.includes(`from 'lapikit/vite'`)) {
143
+ terminal('info', `Lapikit import already exists in ${viteConfigFile}`);
144
+ return;
145
+ }
146
+
147
+ const lines = content.split('\n');
148
+ let importInsertIndex = -1;
149
+ let pluginAdded = false;
150
+
151
+ // Find where to insert the import (after other imports)
152
+ for (let i = 0; i < lines.length; i++) {
153
+ const line = lines[i].trim();
154
+
155
+ if (line.startsWith('import ') && !line.includes('type ')) {
156
+ importInsertIndex = i + 1;
157
+ } else if (
158
+ line === '' &&
159
+ importInsertIndex !== -1 &&
160
+ lines[i + 1] &&
161
+ !lines[i + 1].trim().startsWith('import ')
162
+ ) {
163
+ importInsertIndex = i;
164
+ break;
165
+ }
166
+ }
167
+
168
+ // If no imports found, insert at the beginning
169
+ if (importInsertIndex === -1) {
170
+ importInsertIndex = 0;
171
+ }
172
+
173
+ // Insert the lapikit import
174
+ lines.splice(importInsertIndex, 0, lapikitImport);
175
+
176
+ // Find and update the plugins array
177
+ for (let i = 0; i < lines.length; i++) {
178
+ const line = lines[i].trim();
179
+
180
+ if (line.includes('plugins:') && line.includes('[') && line.includes(']')) {
181
+ // Single line plugins array
182
+ if (line.includes('sveltekit()')) {
183
+ const pluginMatch = line.match(/plugins:\s*\[(.*)\]/);
184
+ if (pluginMatch) {
185
+ const pluginsContent = pluginMatch[1];
186
+ if (!pluginsContent.includes('lapikit()')) {
187
+ const newPluginsContent = pluginsContent.replace(
188
+ /sveltekit\(\)/,
189
+ 'sveltekit(), lapikit()'
190
+ );
191
+ lines[i] = line.replace(pluginsContent, newPluginsContent);
192
+ pluginAdded = true;
193
+ }
194
+ }
195
+ }
196
+ break;
197
+ } else if (line.includes('plugins:') && line.includes('[') && !line.includes(']')) {
198
+ // Multi-line plugins array start
199
+ for (let j = i; j < lines.length; j++) {
200
+ const pluginLine = lines[j].trim();
201
+
202
+ if (pluginLine.includes('sveltekit()') && !pluginAdded) {
203
+ // Check if lapikit() is not already present
204
+ let hasLapikit = false;
205
+ for (let k = i; k < lines.length && !lines[k].includes(']'); k++) {
206
+ if (lines[k].includes('lapikit()')) {
207
+ hasLapikit = true;
208
+ break;
209
+ }
210
+ }
211
+
212
+ if (!hasLapikit) {
213
+ // Add lapikit() after sveltekit()
214
+ if (pluginLine.includes(',')) {
215
+ lines[j] = lines[j].replace('sveltekit()', 'sveltekit(), lapikit()');
216
+ } else {
217
+ lines[j] = lines[j].replace('sveltekit()', 'sveltekit(),');
218
+ // Insert lapikit() on the next line with proper indentation
219
+ const indentation = lines[j].match(/^\s*/)[0];
220
+ lines.splice(j + 1, 0, `${indentation}lapikit()`);
221
+ }
222
+ pluginAdded = true;
223
+ }
224
+ break;
225
+ }
226
+
227
+ if (pluginLine.includes(']')) {
228
+ break;
229
+ }
230
+ }
231
+ break;
232
+ }
233
+ }
234
+
235
+ if (!pluginAdded) {
236
+ terminal('warn', `Could not find sveltekit() in plugins array to add lapikit() after it`);
237
+ }
238
+
239
+ const newContent = lines.join('\n');
240
+ await fs.writeFile(viteConfigFile, newContent);
241
+ terminal('info', `Lapikit import and plugin added to ${viteConfigFile}`);
242
+ } catch (error) {
243
+ terminal('error', `Error adding lapikit to vite config: ${error.message}`);
244
+ throw error;
245
+ }
246
+ }
247
+
248
+ export async function initConfiguration(options) {
249
+ const { typescript, pathConfig, formatCSS } = options;
250
+ const ext = typescript ? 'ts' : 'js';
251
+ const targetDir = path.resolve(process.cwd(), pathConfig);
252
+ const targetFile = path.join(targetDir, `lapikit.${ext}`);
253
+
254
+ await fs.mkdir(targetDir, { recursive: true });
255
+
256
+ let fileCreated = false;
257
+
258
+ // Create Lapikit config
259
+ try {
260
+ await fs.access(targetFile);
261
+ terminal('info', `File ${targetFile} already exists.`);
262
+ } catch {
263
+ terminal('info', `Creating file: ${targetFile}`);
264
+ const content = presets({
265
+ adapterCSS: formatCSS
266
+ });
267
+ await fs.writeFile(targetFile, content);
268
+ terminal('info', `File created: ${targetFile}`);
269
+ fileCreated = true;
270
+ }
271
+
272
+ // Add Import Lapikit plugin
273
+ try {
274
+ const referenceFile = await findReferenceFile(process.cwd());
275
+ await addImportToReferenceFile(targetFile, referenceFile);
276
+ } catch (error) {
277
+ terminal('error', `Error adding import: ${error.message}`);
278
+
279
+ if (fileCreated) {
280
+ try {
281
+ await fs.unlink(targetFile);
282
+ terminal('info', `File ${targetFile} deleted due to error.`);
283
+ } catch {
284
+ // Ignore deletion error
285
+ }
286
+ }
287
+ throw error;
288
+ }
289
+
290
+ // Add lapikit to vite.config file
291
+ try {
292
+ const viteConfigFile = await findViteConfigFile(process.cwd(), typescript);
293
+ await addLapikitToViteConfig(viteConfigFile);
294
+ } catch (error) {
295
+ terminal('warn', `Warning: Could not update vite.config file: ${error.message}`);
296
+ terminal('error', `Error adding lapikit to vite config: ${error.message}`);
297
+ }
298
+ }
package/bin/helper.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { promises as fs } from 'fs';
2
+ import path from 'path';
3
+
1
4
  const color = {
2
5
  red: (text) => `\x1b[31m${text}\x1b[0m`,
3
6
  green: (text) => `\x1b[32m${text}\x1b[0m`,
@@ -63,6 +66,26 @@ export function getCssPathFromArgs() {
63
66
  return args[1] || 'src/app.css';
64
67
  }
65
68
 
69
+ export function getLapikitPathFromArgs() {
70
+ const args = process.argv.slice(2);
71
+ // Search argument after --plugin-path or -p
72
+ const pluginPathIndex = args.findIndex((arg) => arg === '--plugin-path' || arg === '-p');
73
+ if (pluginPathIndex !== -1 && args[pluginPathIndex + 1]) {
74
+ return args[pluginPathIndex + 1];
75
+ }
76
+ return 'src/plugin';
77
+ }
78
+
79
+ export function validatePluginPath(pluginPath) {
80
+ if (!pluginPath.startsWith('src/')) {
81
+ return {
82
+ valid: false,
83
+ error: 'The path must start with "src/"'
84
+ };
85
+ }
86
+ return { valid: true };
87
+ }
88
+
66
89
  export async function envTypescript() {
67
90
  const directory = process.cwd();
68
91
  try {
package/bin/index.js ADDED
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ import { initConfiguration } from './configuration.js';
3
+ import { ansi, terminal } from './helper.js';
4
+ import { legacyConfiguration } from './legacy.js';
5
+ import { initPrompts } from './prompts.js';
6
+
7
+ async function run() {
8
+ console.log(' _ _ _ _ _ ');
9
+ console.log(' | | (_) | (_) | ');
10
+ console.log(' | | __ _ _ __ _| | ___| |_ ');
11
+ console.log(" | | / _` | '_ \\| | |/ / | __|");
12
+ console.log(' | |___| (_| | |_) | | <| | |_ ');
13
+ console.log(' |______\\__,_| .__/|_|_|\\_\\_|\\__|');
14
+ console.log(' | | ');
15
+ console.log(' |_| \n');
16
+
17
+ terminal('none', `${ansi.bold.blue('Lapikit')} - Component Library for Svelte\n\n`);
18
+
19
+ const promptsConfig = await initPrompts();
20
+
21
+ if (promptsConfig.env === 'current') {
22
+ await legacyConfiguration(promptsConfig);
23
+ }
24
+
25
+ if (promptsConfig.env === 'experimental') {
26
+ terminal('warn', `Experimental mode is not yet implemented.`);
27
+ await initConfiguration(promptsConfig);
28
+ }
29
+ }
30
+
31
+ run()
32
+ .then(() => {
33
+ terminal('none', `\n\n\n\nWebsite: https://lapikit.dev`);
34
+ terminal('none', `Github: https://github.com/nycolaide/lapikit`);
35
+ terminal('none', `Support the developement: https://buymeacoffee.com/nycolaide`);
36
+ process.exit(0);
37
+ })
38
+ .catch((error) => {
39
+ terminal('error', `Error: ${error}`);
40
+ process.exit(1);
41
+ });
package/bin/lapikit.js CHANGED
@@ -1,9 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { promises as fs } from 'fs';
3
3
  import path from 'path';
4
- import { ansi, terminal, envTypescript } from './helper.js';
4
+ import {
5
+ ansi,
6
+ terminal,
7
+ envTypescript,
8
+ getLapikitPathFromArgs,
9
+ validatePluginPath
10
+ } from './helper.js';
5
11
  import { preset } from './modules/preset.js';
6
12
  import { adapterCSSConfig, adapterViteConfig } from './modules/adapter.js';
13
+ import { createPluginStructure, setupSvelteKitIntegration } from './modules/plugin.js';
7
14
 
8
15
  const [, , command] = process.argv;
9
16
  const typescriptEnabled = envTypescript();
@@ -11,8 +18,9 @@ const typescriptEnabled = envTypescript();
11
18
  if (process.argv.includes('--help') || process.argv.includes('-h')) {
12
19
  terminal(
13
20
  'info',
14
- `usage: ${ansi.color.yellow('npx lapikit init {cssPath}')}\n\n ${ansi.variant.bold('options:')}\n
15
- - {cssPath}: (${ansi.color.cyan('src/app.css')}) customize path on your origin css file.\n\n`
21
+ `usage: ${ansi.color.yellow('npx lapikit init {cssPath} [--plugin-path {pluginPath}]')}\n\n ${ansi.variant.bold('options:')}\n
22
+ - {cssPath}: (${ansi.color.cyan('src/app.css')}) customize path on your origin css file.
23
+ - --plugin-path, -p: (${ansi.color.cyan('src/plugin')}) customize path for the plugin directory.\n\n`
16
24
  );
17
25
  process.exit(0);
18
26
  } else if (command === 'init') {
@@ -27,6 +35,15 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {
27
35
 
28
36
  terminal('none', `${ansi.bold.blue('LAPIKIT')} - Component Library for Svelte\n\n`);
29
37
 
38
+ // Get Path
39
+ const pluginPath = getLapikitPathFromArgs();
40
+ const pathValidation = validatePluginPath(pluginPath);
41
+
42
+ if (!pathValidation.valid) {
43
+ terminal('error', `Invalid path: ${pathValidation.error}`);
44
+ process.exit(1);
45
+ }
46
+
30
47
  const configPath = path.resolve(process.cwd(), 'lapikit.config.js');
31
48
  try {
32
49
  await fs.writeFile(configPath, preset.trim() + '\n', 'utf8');
@@ -39,6 +56,20 @@ if (process.argv.includes('--help') || process.argv.includes('-h')) {
39
56
  );
40
57
  }
41
58
 
59
+ // Create plugin structure
60
+ try {
61
+ await createPluginStructure(pluginPath, typescriptEnabled);
62
+ } catch (error) {
63
+ terminal('error', `Create plugin structure not working : ${error.message}`);
64
+ }
65
+
66
+ // Setup SvelteKit integration
67
+ try {
68
+ await setupSvelteKitIntegration(pluginPath, typescriptEnabled);
69
+ } catch (error) {
70
+ terminal('error', `SvelteKit integration setup failed: ${error.message}`);
71
+ }
72
+
42
73
  await adapterViteConfig(typescriptEnabled);
43
74
  await adapterCSSConfig();
44
75
 
package/bin/legacy.js ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { preset } from './modules/preset.js';
5
+ import { ansi, terminal, envTypescript } from './helper.js';
6
+ import { adapterCSSConfig, adapterViteConfig } from './modules/adapter.js';
7
+
8
+ export async function legacyConfiguration(options) {
9
+ const typescriptEnabled = envTypescript();
10
+ const configPath = path.resolve(process.cwd(), 'lapikit.config.js');
11
+
12
+ try {
13
+ await fs.writeFile(configPath, preset.trim() + '\n', 'utf8');
14
+ terminal('success', `has create lapikit.config.js on your project.`);
15
+ } catch (error) {
16
+ terminal('error', `failed to create configuration file:\n\n ${error}`);
17
+ terminal(
18
+ 'warn',
19
+ `you can create lapikit.config.js manually, please visite https://lapikit.dev/docs/getting-started for more information`
20
+ );
21
+ }
22
+
23
+ await adapterViteConfig(typescriptEnabled);
24
+ await adapterCSSConfig(options);
25
+
26
+ terminal(
27
+ 'info',
28
+ `${ansi.bold.blue('Thank to use lapikit, discover all posibility with lapikit on https://lapikit.dev')}\n\n`
29
+ );
30
+
31
+ console.log('Website: https://lapikit.dev');
32
+ console.log('Github: https://github.com/nycolaide/lapikit');
33
+ console.log('Support the developement: https://buymeacoffee.com/nycolaide');
34
+ }
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import path from 'path';
3
- import { getCssPathFromArgs, terminal } from '../helper.js';
3
+ import { terminal } from '../helper.js';
4
4
 
5
5
  const importLapikitVite = `import { lapikit } from 'lapikit/vite';`;
6
6
  const importLapikitCss = `@import 'lapikit/css';`;
@@ -33,8 +33,8 @@ export async function adapterViteConfig(typescript) {
33
33
  }
34
34
  }
35
35
 
36
- export async function adapterCSSConfig() {
37
- const cssPath = getCssPathFromArgs();
36
+ export async function adapterCSSConfig(options) {
37
+ const cssPath = options?.pathCSS || 'src/app.css';
38
38
  const resolvedPath = path.resolve(process.cwd(), cssPath);
39
39
  try {
40
40
  await fs.access(resolvedPath);