@digigov/cli-build 2.0.0-254f7786 → 2.0.0-290ada95

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/copy-files.js CHANGED
@@ -1,7 +1,6 @@
1
- import { logger, resolveProject } from "@digigov/cli/lib";
2
- import fs from "fs-extra";
3
- import path from "path";
4
- import glob from "globby";
1
+ import { logger, resolveProject } from '@digigov/cli/lib';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
5
4
 
6
5
  const packagePath = process.cwd();
7
6
  const project = resolveProject();
@@ -24,53 +23,29 @@ function includeFileInBuild(file) {
24
23
  */
25
24
  function createRootPackageFile() {
26
25
  const packageData = fs.readFileSync(
27
- path.resolve(packagePath, "./package.json"),
28
- "utf8",
26
+ path.resolve(packagePath, './package.json'),
27
+ 'utf8'
29
28
  );
29
+
30
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
30
31
  const { nyc, scripts, devDependencies, workspaces, ...packageDataOther } =
31
32
  JSON.parse(packageData);
32
33
  const newPackageData = {
33
34
  ...packageDataOther,
34
35
  private: false,
35
- main: "./cjs/index.js",
36
- module: "./index.js",
37
- typings: "./index.d.ts",
36
+ exports: undefined,
37
+ main: 'index.js',
38
+ module: 'index.js',
39
+ type: 'module', // ESM only
38
40
  };
39
- const targetPath = path.resolve(buildPath, "./package.json");
41
+ const targetPath = path.resolve(buildPath, './package.json');
40
42
 
41
- fs.writeFileSync(targetPath, JSON.stringify(newPackageData, null, 2), "utf8");
43
+ fs.writeFileSync(targetPath, JSON.stringify(newPackageData, null, 2), 'utf8');
42
44
  logger.debug(`Created package.json in build directory`);
43
45
 
44
46
  return newPackageData;
45
47
  }
46
48
 
47
- /**
48
- * Create nested package.json files in the build directory
49
- *
50
- */
51
- function createNestedPackageFiles() {
52
- const indexPaths = glob.sync(path.join(buildPath, "**/index.js"), {
53
- ignore: [path.join(buildPath, "cjs/**")],
54
- });
55
-
56
- indexPaths.forEach((indexPath) => {
57
- if (indexPath === path.join(buildPath, "index.js")) return;
58
- const packageData = {
59
- sideEffects: false,
60
- module: "./index.js",
61
- types: "./index.d.ts",
62
- main: path.relative(
63
- path.dirname(indexPath),
64
- indexPath.replace(buildPath, path.join(buildPath, "/cjs")),
65
- ),
66
- };
67
- fs.writeFileSync(
68
- path.join(path.dirname(indexPath), "package.json"),
69
- JSON.stringify(packageData, null, 2),
70
- );
71
- });
72
- }
73
-
74
49
  /**
75
50
  * Prepend a string to a file
76
51
  *
@@ -78,8 +53,8 @@ function createNestedPackageFiles() {
78
53
  * @param {string} string - The string to prepend
79
54
  */
80
55
  function prepend(file, string) {
81
- const data = fs.readFileSync(file, "utf8");
82
- fs.writeFileSync(file, string + data, "utf8");
56
+ const data = fs.readFileSync(file, 'utf8');
57
+ fs.writeFileSync(file, string + data, 'utf8');
83
58
  logger.debug(`Prepended license to ${file}`);
84
59
  }
85
60
 
@@ -89,21 +64,21 @@ function prepend(file, string) {
89
64
  * @param {object} packageData - The package data
90
65
  */
91
66
  function addLicense(packageData) {
92
- const license = `/** @license Digigov v${packageData["version"]}
67
+ const license = `/** @license Digigov v${packageData['version']}
93
68
  *
94
69
  * This source code is licensed under the BSD-2-Clause license found in the
95
70
  * LICENSE file in the root directory of this source tree.
96
71
  */
97
72
  `;
98
- ["./index.js", "./index.mjs"].map(async (file) => {
73
+ ['./index.js', './index.mjs'].map(async (file) => {
99
74
  try {
100
75
  prepend(path.resolve(buildPath, file), license);
101
76
  } catch (err) {
102
77
  if (
103
- typeof err === "object" &&
78
+ typeof err === 'object' &&
104
79
  err &&
105
- "code" in err &&
106
- err.code === "ENOENT"
80
+ 'code' in err &&
81
+ err.code === 'ENOENT'
107
82
  ) {
108
83
  logger.debug(`Skipped license for ${file}`);
109
84
  } else {
@@ -113,35 +88,19 @@ function addLicense(packageData) {
113
88
  });
114
89
  }
115
90
 
116
- /**
117
- * Create separate index modules for each directory
118
- */
119
- function createSeparateIndexModules() {
120
- const files = glob.sync(path.join(buildPath, "**/*.js"), {
121
- ignore: [path.join(buildPath, "**/index.js")],
122
- });
123
-
124
- files.forEach((file) => {
125
- fs.mkdirSync(file.replace(/\.js$/, ""));
126
- fs.renameSync(file, file.replace(/\.js$/, "/index.js"));
127
- });
128
- }
129
-
130
91
  /**
131
92
  * Run the copy files script
132
93
  */
133
94
  export default function run() {
134
95
  const packageData = createRootPackageFile();
135
- createSeparateIndexModules();
136
- createNestedPackageFiles();
137
96
 
138
97
  [
139
98
  // use enhanced readme from workspace root for `@digigov/ui`
140
99
  // packageData.name === '@digigov/ui' ? '../../README.md' : './README.md',
141
- "./src",
142
- "./README.md",
143
- "./CHANGELOG.md",
144
- "../../LICENSE",
145
- ].map((file) => includeFileInBuild(file)),
146
- addLicense(packageData);
100
+ './src',
101
+ './README.md',
102
+ './CHANGELOG.md',
103
+ '../../LICENSE',
104
+ ].map((file) => includeFileInBuild(file));
105
+ addLicense(packageData);
147
106
  }
@@ -0,0 +1,3 @@
1
+ import config from '@digigov/cli-lint/eslint.config';
2
+
3
+ export default [...config];
@@ -1,86 +1,40 @@
1
- import { logger } from "@digigov/cli/lib";
2
- import path from "path";
3
- import fs from "fs-extra";
4
- import { SyntaxKind, Project as TsMorphProject } from "ts-morph";
5
- import assert from "assert";
6
-
7
- import { getProjectTsconfig } from "./common.js";
8
-
9
- /**
10
- * Generate registry files for the given project
11
- *
12
- * @param {object} project - The project object
13
- * @param {string} project.root - The project root directory
14
- * @param {string} project.distDir - The project build directory
15
- * @param {string} project.name - The project name as in package.json
16
- * @param {string[]} filePaths - The paths of the files to include in the registry
17
- * @param {boolean} shouldGenerateStoriesRegistry - Whether to export stories in the registry
18
- * @returns {Promise<[string, string]>} - The paths of the generated registry files
19
- */
20
- export async function generateRegistryFiles(
21
- project,
22
- filePaths,
23
- shouldGenerateStoriesRegistry = false,
24
- ) {
25
- const registryPath = ensureRegistryPath(project, "registry.js");
26
- const lazyRegistryPath = ensureRegistryPath(project, "lazy.js");
27
-
28
- const registry = generateRegistryFileContent(
29
- project,
30
- filePaths,
31
- shouldGenerateStoriesRegistry,
32
- );
33
-
34
- const componentPathsOnly = filePaths.filter(
35
- (path) => !path.includes("stories"),
36
- );
37
- const lazyRegistry = generateLazyFileContent(project, componentPathsOnly);
38
-
39
- await Promise.all([
40
- fs.writeFile(registryPath, registry),
41
- fs.writeFile(lazyRegistryPath, lazyRegistry),
42
- ]);
43
-
44
- return [registryPath, lazyRegistryPath];
45
- }
46
-
47
- /**
48
- * Ensure that the registry file does not already exist at the given path
49
- *
50
- * @param {object} project - The project object
51
- * @param {string} project.root - The project root directory
52
- * @param {string} project.distDir - The project build directory
53
- * @param {string} fileName - The name of the registry file
1
+ import { logger } from '@digigov/cli/lib';
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
4
+ import { SyntaxKind, Project as TsMorphProject } from 'ts-morph';
5
+ import assert from 'assert';
6
+
7
+ import { getProjectTsconfig } from './common.js';
8
+
9
+ /** @typedef {Object} Project - Represents the project to be built
10
+ * @property {string} root - The project root directory
11
+ * @property {string} name - The project name as in package.json
12
+ * @property {string} src - The project src directory
13
+ * @property {string} distDir - The project build directory
54
14
  */
55
- function ensureRegistryPath(project, fileName) {
56
- const registryPath = path.join(project.root, project.distDir, fileName);
57
- if (fs.existsSync(registryPath))
58
- throw new Error(`A "${fileName}" file already exists at ${registryPath}.`);
59
- return registryPath;
60
- }
61
15
 
62
16
  /**
63
- * Generate registry file content for the given files
17
+ * Generate registry file for the given project
64
18
  *
65
- * @param {object} project - The project object
66
- * @param {string} project.root - The project root directory
67
- * @param {string} project.name - The project name as in package.json
19
+ * @param {Project} project - The project object
20
+ * @param {string} [registryFilename="registry.js"] - The name of the registry file
68
21
  * @param {string[]} absoluteFilePaths - The absolute paths of the files to include in the registry
69
- * @param {boolean} includeStories - Whether to include stories in the registry
70
- * @returns {string} - The registry file content or null if no components are found
22
+ * @returns {Promise<string>} - The path to the generated registry file
71
23
  */
72
- export function generateRegistryFileContent(
24
+ export async function generateRegistry(
73
25
  project,
74
26
  absoluteFilePaths,
75
- includeStories = false,
27
+ registryFilename = 'registry.js'
76
28
  ) {
29
+ const registryPath = ensureRegistryPath(project, registryFilename);
30
+
77
31
  const relativePaths = absoluteFilePaths.map((path) => {
78
32
  assert(
79
33
  path.startsWith(project.root),
80
- "Expected path to be in project root",
34
+ 'Expected path to be in project root'
81
35
  );
82
36
  return toNodeResolvablePath(
83
- path.replace(`${project.root}/src/`, `${project.name}/`),
37
+ path.replace(`${project.root}/src/`, `${project.name}/`)
84
38
  );
85
39
  });
86
40
  let registryPaths = relativePaths.map((path) => ({
@@ -90,25 +44,22 @@ export function generateRegistryFileContent(
90
44
 
91
45
  if (registryPaths.length === 0)
92
46
  throw new Error(
93
- "Could not generate registry. No exportable modules found.",
47
+ 'Could not generate registry. No exportable modules found.'
94
48
  );
95
49
 
96
50
  const importStatements = registryPaths.map(
97
- (file) => `import * as ${file.uid} from "${file.path}";`,
51
+ (file) => `import * as ${file.uid} from "${file.path}";`
98
52
  );
99
- const exportStatements = registryPaths.map(
100
- (file) => ` '${file.path}': lazyImport(${file.uid})`,
53
+ const componentsToExport = registryPaths.map(
54
+ (file) => ` '${file.path}': lazyImport(${file.uid})`
101
55
  );
102
56
 
103
- const [components, stories] = splitStoriesExports(exportStatements);
104
- logger.debug(`Including ${components.length} component modules in registry`);
105
-
106
- if (includeStories) {
107
- logger.debug(`Including ${stories.length} stories in registry`);
108
- }
57
+ logger.debug(
58
+ `Including ${componentsToExport.length} items in ${registryPath}`
59
+ );
109
60
 
110
- let out = `
111
- ${importStatements.join("\n")}
61
+ let registryFileContent = `
62
+ ${importStatements.join('\n')}
112
63
  function lazyImport(pkgImport) {
113
64
  return new Proxy(
114
65
  {},
@@ -128,73 +79,29 @@ function lazyImport(pkgImport) {
128
79
  )
129
80
  }
130
81
  export default {
131
- ${components.join(",\n")}
132
- };
133
- `;
134
-
135
- if (includeStories) {
136
- out += `
137
-
138
- export const stories = {
139
- ${stories.join(",\n")}
82
+ ${componentsToExport.join(',\n')}
140
83
  };
141
84
  `;
142
- }
143
- return out;
144
- }
145
-
146
- /**
147
- * Extract a node-resolvable path
148
- *
149
- * @param {string} inputPath - The file path
150
- * @returns {string} - The node-resolvable path
151
- */
152
- export function toNodeResolvablePath(inputPath) {
153
- const dir = path.dirname(inputPath);
154
- const base = path.basename(inputPath, path.extname(inputPath));
155
-
156
- return base === "index" ? dir : path.join(dir, base);
157
- }
158
-
159
- /**
160
- * Create a UID from a path
161
- *
162
- * @param {string} inputPath - The path
163
- * @returns {string} - The UID
164
- */
165
- export function createUid(inputPath) {
166
- return inputPath.replace(/[\/@\-.]/g, "_");
167
- }
85
+ await fs.writeFile(registryPath, registryFileContent);
168
86
 
169
- /**
170
- * Split the given files into components and stories
171
- *
172
- * @param {string[]} exportStatements - The export statements
173
- * @returns {[string[], string[]]} - The split components and stories exports
174
- */
175
- export function splitStoriesExports(exportStatements) {
176
- const stories = [];
177
- const components = [];
178
- for (const exportStatement of exportStatements) {
179
- if (exportStatement.includes("_stories")) {
180
- stories.push(exportStatement);
181
- } else {
182
- components.push(exportStatement);
183
- }
184
- }
185
- return [components, stories];
87
+ return registryPath;
186
88
  }
187
89
 
188
90
  /**
189
- * Generate lazy component registry file content for the given project
91
+ * Generate a lazy registry file for the given project
190
92
  *
191
- * @param {object} project - The project object
192
- * @param {string} project.root - The project root directory
193
- * @param {string} project.name - The project name as in package.json
93
+ * @param {Project} project - The project object
194
94
  * @param {string[]} filePaths - The files whose exports will be included in the lazy registry
195
- * @returns {string} - The lazy component registry file content or null if no components are found
95
+ * @param {string} [lazyFilename="lazy.js"] - The name of the registry file
96
+ * @returns {Promise<string>} - The path to the generated lazy registry file
196
97
  */
197
- export function generateLazyFileContent(project, filePaths) {
98
+ export async function generateLazyRegistry(
99
+ project,
100
+ filePaths,
101
+ lazyFilename = 'lazy.js'
102
+ ) {
103
+ const lazyPath = ensureRegistryPath(project, lazyFilename);
104
+
198
105
  const tsMorphProject = new TsMorphProject({
199
106
  tsConfigFilePath: getProjectTsconfig(project.root),
200
107
  });
@@ -211,15 +118,15 @@ export function generateLazyFileContent(project, filePaths) {
211
118
 
212
119
  for (const exportedComponent of exports) {
213
120
  if (
214
- exportedComponent !== "default" &&
215
- exportedComponent.match(/^[A-Z]/)
121
+ exportedComponent !== 'default' &&
122
+ exportedComponent.match(/^[A-Z][a-z]+/)
216
123
  ) {
217
124
  if (
218
125
  !allComponents[exportedComponent] ||
219
126
  allComponents[exportedComponent].length < filePath.length // Make import path more specific
220
127
  ) {
221
128
  allComponents[exportedComponent] = toNodeResolvablePath(
222
- filePath.replace(`${project.root}/src/`, `${project.name}/`),
129
+ filePath.replace(`${project.root}/src/`, `${project.name}/`)
223
130
  );
224
131
  }
225
132
  }
@@ -230,23 +137,63 @@ export function generateLazyFileContent(project, filePaths) {
230
137
 
231
138
  if (componentCount === 0)
232
139
  throw new Error(
233
- "Could not generate lazy registry. No exportable components found.",
140
+ 'Could not generate lazy registry. No exportable components found.'
234
141
  );
235
142
 
236
- logger.debug(`Including ${componentCount} components in lazy registry`);
143
+ logger.debug(`Including ${componentCount} components in ${lazyPath}`);
237
144
 
238
- const content = Object.entries(allComponents)
145
+ const componentsToExport = Object.entries(allComponents)
239
146
  .map(
240
147
  ([component, filePath]) =>
241
- ` '${component}': lazy(() => import('${filePath}').then((module) => ({ default: module['${component}'] })))`,
148
+ ` '${component}': lazy(() => import('${filePath}').then((module) => ({ default: module['${component}'] })))`
242
149
  )
243
- .join(",\n");
150
+ .join(',\n');
244
151
 
245
- return `import { lazy } from 'react';
152
+ const lazyFileContent = `import { lazy } from 'react';
246
153
  export default {
247
- ${content}
154
+ ${componentsToExport}
248
155
  };
249
156
  `;
157
+
158
+ await fs.writeFile(lazyPath, lazyFileContent);
159
+
160
+ return lazyPath;
161
+ }
162
+
163
+ /**
164
+ * Ensure that the registry file does not already exist at the given path
165
+ *
166
+ * @param {Project} project - The project object
167
+ * @param {string} fileName - The name of the registry file
168
+ */
169
+ function ensureRegistryPath(project, fileName) {
170
+ const registryPath = path.join(project.root, project.src, fileName);
171
+ if (fs.existsSync(registryPath))
172
+ throw new Error(`A "${fileName}" file already exists at ${registryPath}.`);
173
+ return registryPath;
174
+ }
175
+
176
+ /**
177
+ * Extract a node-resolvable path
178
+ *
179
+ * @param {string} inputPath - The file path
180
+ * @returns {string} - The node-resolvable path
181
+ */
182
+ function toNodeResolvablePath(inputPath) {
183
+ const dir = path.dirname(inputPath);
184
+ const base = path.basename(inputPath, path.extname(inputPath));
185
+
186
+ return base === 'index' ? dir : path.join(dir, base);
187
+ }
188
+
189
+ /**
190
+ * Create a UID from a path
191
+ *
192
+ * @param {string} inputPath - The path
193
+ * @returns {string} - The UID
194
+ */
195
+ function createUid(inputPath) {
196
+ return inputPath.replace(/[/@\-.]/g, '_');
250
197
  }
251
198
 
252
199
  /**