jiek 0.2.1 → 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.
package/dist/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('node:fs'), require('node:path'), require('@jiek/utils/getWorkspaceDir'), require('@pnpm/filter-workspace-packages'), require('commander'), require('js-yaml'), require('@jiek/utils/bumper'), require('child_process'), require('detect-indent'), require('jsonc-parser'), require('@jiek/pkger'), require('node:child_process')) :
3
- typeof define === 'function' && define.amd ? define(['node:fs', 'node:path', '@jiek/utils/getWorkspaceDir', '@pnpm/filter-workspace-packages', 'commander', 'js-yaml', '@jiek/utils/bumper', 'child_process', 'detect-indent', 'jsonc-parser', '@jiek/pkger', 'node:child_process'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.fs, global.path, global.getWorkspaceDir, global.filterWorkspacePackages, global.commander, global.jsYaml, global.bumper, global.childProcess, global.detectIndent, global.jsoncParser, global.pkger, global.childProcess$1));
5
- })(this, (function (fs, path, getWorkspaceDir, filterWorkspacePackages, commander, jsYaml, bumper, childProcess, detectIndent, jsoncParser, pkger, childProcess$1) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('node:fs'), require('node:path'), require('@pnpm/filter-workspace-packages'), require('commander'), require('js-yaml'), require('@jiek/utils/getWorkspaceDir'), require('node:child_process'), require('@jiek/pkger'), require('detect-indent'), require('inquirer'), require('jsonc-parser'), require('micromatch'), require('@jiek/utils/bumper'), require('child_process')) :
3
+ typeof define === 'function' && define.amd ? define(['node:fs', 'node:path', '@pnpm/filter-workspace-packages', 'commander', 'js-yaml', '@jiek/utils/getWorkspaceDir', 'node:child_process', '@jiek/pkger', 'detect-indent', 'inquirer', 'jsonc-parser', 'micromatch', '@jiek/utils/bumper', 'child_process'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.fs, global.path, global.filterWorkspacePackages, global.commander, global.jsYaml, global.getWorkspaceDir, global.childProcess, global.pkger, global.detectIndent, global.inquirer, global.jsoncParser, global.micromatch, global.bumper, global.childProcess$1));
5
+ })(this, (function (fs, path, filterWorkspacePackages, commander, jsYaml, getWorkspaceDir, childProcess, pkger, detectIndent, inquirer, jsoncParser, micromatch, bumper, childProcess$1) { 'use strict';
6
6
 
7
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
 
@@ -28,23 +28,24 @@
28
28
  var path__default = /*#__PURE__*/_interopDefault(path);
29
29
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
30
30
  var detectIndent__default = /*#__PURE__*/_interopDefault(detectIndent);
31
+ var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
31
32
  var childProcess__namespace$1 = /*#__PURE__*/_interopNamespace(childProcess$1);
32
33
 
33
- let type = "";
34
- try {
35
- require.resolve("@pnpm/filter-workspace-packages");
36
- type = "pnpm";
37
- } catch {
38
- }
39
- if (type !== "") {
40
- commander.program.option("-f, --filter <filter>", "filter packages");
41
- }
42
- async function getSelectedProjectsGraph() {
43
- let filter = commander.program.getOptionValue("filter");
34
+ let root;
35
+ function getRoot() {
36
+ if (root)
37
+ return root;
44
38
  const rootOption = commander.program.getOptionValue("root");
45
- const root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : process.cwd();
46
- let notWorkspace = false;
47
- let wd;
39
+ root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : process.cwd();
40
+ return root;
41
+ }
42
+
43
+ let wd;
44
+ let notWorkspace = false;
45
+ function getWD() {
46
+ if (wd)
47
+ return { wd, notWorkspace };
48
+ const root = getRoot();
48
49
  try {
49
50
  wd = getWorkspaceDir.getWorkspaceDir(root, type);
50
51
  } catch (e) {
@@ -55,6 +56,22 @@
55
56
  throw e;
56
57
  }
57
58
  }
59
+ return { wd, notWorkspace };
60
+ }
61
+
62
+ let type = "";
63
+ try {
64
+ require.resolve("@pnpm/filter-workspace-packages");
65
+ type = "pnpm";
66
+ } catch {
67
+ }
68
+ if (type !== "") {
69
+ commander.program.option("-f, --filter <filter>", "filter packages");
70
+ }
71
+ async function getSelectedProjectsGraph() {
72
+ let filter = commander.program.getOptionValue("filter");
73
+ const root = getRoot();
74
+ const { wd, notWorkspace } = getWD();
58
75
  if (!notWorkspace && type === "pnpm") {
59
76
  const pnpmWorkspaceFilePath = path__default.default.resolve(wd, "pnpm-workspace.yaml");
60
77
  const pnpmWorkspaceFileContent = fs__default.default.readFileSync(pnpmWorkspaceFilePath, "utf-8");
@@ -179,6 +196,398 @@
179
196
  };
180
197
  }
181
198
 
199
+ const FILE_TEMPLATE = (manifest) => `
200
+ const pkg = ${JSON.stringify(manifest, null, 2)}
201
+ const { jiek = {} } = pkg
202
+ const templateArg = jiek.templateArgFilePath
203
+ ? require.resolve(jiek.templateArgFilePath)
204
+ : {
205
+ styled: jiek.styled
206
+ }
207
+ module.exports = require('jiek/rollup').template(templateArg, pkg)
208
+ `.trimStart();
209
+ commander.program.command("build").action(async () => {
210
+ actionRestore();
211
+ const {
212
+ wd,
213
+ value = {}
214
+ } = await getSelectedProjectsGraph() ?? {};
215
+ if (Object.keys(value).length === 0) {
216
+ throw new Error("no package found");
217
+ }
218
+ const jiekTempDir = (...paths) => path__default.default.resolve(wd, "node_modules/.jiek", ...paths);
219
+ if (!fs__default.default.existsSync(jiekTempDir()))
220
+ fs__default.default.mkdirSync(jiekTempDir());
221
+ const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
222
+ let i = 0;
223
+ for (const [dir, manifest] of Object.entries(value)) {
224
+ const newManifest = mergePackageJson(manifest, dir);
225
+ const escapeManifestName = manifest.name?.replace(/^@/g, "").replace(/\//g, "+");
226
+ const configFile = jiekTempDir(
227
+ `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
228
+ );
229
+ fs__default.default.writeFileSync(configFile, FILE_TEMPLATE(newManifest));
230
+ let prefix = "";
231
+ if (process.env.NODE_ENV === "test") {
232
+ const registerPath = require.resolve("esbuild-register");
233
+ const loaderPath = require.resolve("esbuild-register/loader");
234
+ prefix = `node --import ${registerPath} -r ${loaderPath} `;
235
+ }
236
+ childProcess__namespace.execSync(`${prefix}${rollupBinaryPath} -c ${configFile}`, {
237
+ cwd: dir,
238
+ stdio: "inherit"
239
+ });
240
+ }
241
+ actionDone();
242
+ });
243
+
244
+ function packageIsExist(name) {
245
+ try {
246
+ require.resolve(name);
247
+ return true;
248
+ } catch (e) {
249
+ console.log(e);
250
+ return false;
251
+ }
252
+ }
253
+ let tsRegisterName;
254
+ const registers = [
255
+ process.env.JIEK_TS_REGISTER,
256
+ "esbuild-register"
257
+ ].filter(Boolean);
258
+ for (const register of registers) {
259
+ if (packageIsExist(register)) {
260
+ tsRegisterName = register;
261
+ break;
262
+ }
263
+ }
264
+ let configName = "jiek.config";
265
+ function getConfigPath(root) {
266
+ const isSupportTsLoader = !!tsRegisterName;
267
+ function configWithExtIsExist(ext) {
268
+ const filenames = [
269
+ path__default.default.resolve(root, `${configName}.${ext}`),
270
+ path__default.default.resolve(root, `.${configName}.${ext}`)
271
+ ];
272
+ for (const filename of filenames) {
273
+ if (fs__default.default.existsSync(filename) && fs__default.default.lstatSync(filename).isFile()) {
274
+ return filename;
275
+ }
276
+ }
277
+ return;
278
+ }
279
+ configName = configWithExtIsExist("js") ?? configName;
280
+ configName = configWithExtIsExist("json") ?? configName;
281
+ configName = configWithExtIsExist("yaml") ?? configName;
282
+ if (isSupportTsLoader) {
283
+ configName = configWithExtIsExist("ts") ?? configName;
284
+ }
285
+ return path__default.default.resolve(root, configName);
286
+ }
287
+ function loadConfig() {
288
+ const { wd: root, notWorkspace } = getWD();
289
+ if (notWorkspace)
290
+ throw new Error("not in workspace");
291
+ let configPath = commander.program.getOptionValue("configPath");
292
+ if (!configPath) {
293
+ configPath = getConfigPath(root);
294
+ } else {
295
+ if (!fs__default.default.existsSync(configPath))
296
+ throw new Error(`config file not found: ${configPath}`);
297
+ if (!path__default.default.isAbsolute(configPath))
298
+ configPath = path__default.default.resolve(root, configPath);
299
+ }
300
+ const ext = path__default.default.extname(configPath);
301
+ let module;
302
+ switch (ext) {
303
+ case ".js":
304
+ module = require(configPath);
305
+ break;
306
+ case ".json":
307
+ return require(configPath);
308
+ case ".yaml":
309
+ return jsYaml.load(fs__default.default.readFileSync(configPath, "utf-8"));
310
+ case ".ts":
311
+ if (tsRegisterName) {
312
+ require(tsRegisterName);
313
+ module = require(configPath);
314
+ break;
315
+ }
316
+ throw new Error(
317
+ "ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register"
318
+ );
319
+ case ".config":
320
+ module = {};
321
+ break;
322
+ default:
323
+ throw new Error(`unsupported config file type: ${ext}`);
324
+ }
325
+ if (!module)
326
+ throw new Error("config file is empty");
327
+ return module.default ?? module;
328
+ }
329
+
330
+ const PACKAGE_JSON_TEMPLATE = `{
331
+ "name": "",
332
+ "version": "0.0.1",
333
+ "description": "",
334
+ "license": "",
335
+ "author": "",
336
+ "files": ["dist"],
337
+ "exports": {
338
+ ".": "./src/index.ts"
339
+ },
340
+ "scripts": {
341
+ },
342
+ "homepage": "",
343
+ "repository": "",
344
+ "bugs": ""
345
+ }`.trimStart();
346
+ const README_TEMPLATE = `# $name
347
+
348
+ ## Installation
349
+
350
+ \`\`\`bash
351
+ npm install $name
352
+ # or
353
+ pnpm install $name
354
+ # or
355
+ yarn add $name
356
+ \`\`\`
357
+
358
+ ## Usage
359
+
360
+
361
+ ## License
362
+
363
+ $license
364
+ `.trimStart();
365
+ function getTemplateStr(wd, template) {
366
+ let templateString = template ?? PACKAGE_JSON_TEMPLATE;
367
+ let isTemplateFile = false;
368
+ try {
369
+ if (template)
370
+ JSON.parse(template);
371
+ } catch (e) {
372
+ isTemplateFile = true;
373
+ }
374
+ if (isTemplateFile) {
375
+ const templatePath = path__default.default.resolve(wd, template);
376
+ templateString = fs__default.default.readFileSync(templatePath, "utf-8");
377
+ }
378
+ return templateString;
379
+ }
380
+ const wdCache = /* @__PURE__ */ new Map();
381
+ function getWDPackageJSONFiled(wd, field) {
382
+ if (wdCache.has(wd)) {
383
+ return wdCache.get(wd)[field];
384
+ }
385
+ const packageJSONPath = path__default.default.resolve(wd, "package.json");
386
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(packageJSONPath, "utf-8"));
387
+ wdCache.set(wd, packageJSON);
388
+ return packageJSON[field];
389
+ }
390
+ async function getName(named, name, {
391
+ wd,
392
+ cwd,
393
+ workspaceName
394
+ }) {
395
+ const relativePath = cwd.replace(`${wd}/`, "");
396
+ let basename = path__default.default.basename(cwd);
397
+ if (typeof named === "function") {
398
+ return named(name, {
399
+ full: wd,
400
+ relative: cwd
401
+ });
402
+ }
403
+ let isParentMatched = false;
404
+ let matchedKey;
405
+ let matchedRule;
406
+ if (typeof named === "object") {
407
+ const isWD = cwd === wd;
408
+ if (isWD) {
409
+ const { rule } = await inquirer__default.default.prompt({
410
+ type: "list",
411
+ name: "rule",
412
+ message: "choose a rule",
413
+ default: "default",
414
+ choices: ["default"].concat(Object.keys(named))
415
+ });
416
+ if (rule !== "default") {
417
+ matchedKey = rule;
418
+ matchedRule = named[rule];
419
+ }
420
+ } else
421
+ for (const [key, value] of Object.entries(named)) {
422
+ if (micromatch.isMatch(relativePath, key)) {
423
+ matchedKey = key;
424
+ matchedRule = value;
425
+ break;
426
+ }
427
+ if (micromatch.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
428
+ isParentMatched = true;
429
+ matchedKey = key;
430
+ matchedRule = value;
431
+ break;
432
+ }
433
+ }
434
+ }
435
+ if (!matchedRule) {
436
+ matchedKey = "packages/*";
437
+ matchedRule = `@${workspaceName}/$basename`;
438
+ }
439
+ if (!matchedRule)
440
+ throw new Error("no matched rule");
441
+ if (!name && isParentMatched) {
442
+ basename = await inquirer__default.default.prompt({
443
+ type: "input",
444
+ name: "name",
445
+ message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
446
+ `
447
+ }).then(({ name: name2 }) => name2);
448
+ }
449
+ if (typeof matchedRule === "function") {
450
+ return matchedRule(name, {
451
+ full: wd,
452
+ relative: cwd,
453
+ basename
454
+ });
455
+ }
456
+ if (typeof matchedRule === "string") {
457
+ const dirName = name ?? basename;
458
+ return [
459
+ matchedRule.replace(/\$basename/g, dirName),
460
+ matchedKey?.replace(/\/\*$/g, `/${dirName}`)
461
+ ];
462
+ }
463
+ throw new Error("no matched rule");
464
+ }
465
+ commander.program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
466
+ const [, name] = commander.program.args;
467
+ const cwd = process.cwd();
468
+ const { init = {} } = loadConfig() ?? {};
469
+ const { wd } = getWD();
470
+ const workspaceName = path__default.default.basename(wd);
471
+ const {
472
+ named,
473
+ template,
474
+ bug = {},
475
+ readme: _readme = README_TEMPLATE,
476
+ readmeTemplate
477
+ } = init;
478
+ const resolvedBug = {
479
+ template: "bug_report.yml",
480
+ labels: ["bug"],
481
+ ...bug
482
+ };
483
+ let readme = _readme;
484
+ if (readmeTemplate) {
485
+ const readmeTemplatePath = path__default.default.resolve(wd, readmeTemplate);
486
+ readme = fs__default.default.readFileSync(readmeTemplatePath, "utf-8");
487
+ }
488
+ const templateString = getTemplateStr(wd, template);
489
+ const { indent = " " } = detectIndent__default.default(templateString);
490
+ const formattingOptions = {
491
+ tabSize: indent.length,
492
+ insertSpaces: true
493
+ };
494
+ const passFields = [
495
+ "license",
496
+ "author"
497
+ ];
498
+ let newJSONString = templateString;
499
+ for (const field of passFields) {
500
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
501
+ newJSONString,
502
+ [field],
503
+ getWDPackageJSONFiled(wd, field),
504
+ { formattingOptions }
505
+ ));
506
+ }
507
+ let [pkgName, pkgDir] = await getName(named, name, {
508
+ wd,
509
+ cwd,
510
+ workspaceName
511
+ });
512
+ if (!pkgDir) {
513
+ const { dir } = await inquirer__default.default.prompt({
514
+ type: "input",
515
+ name: "dir",
516
+ message: "package directory",
517
+ default: name
518
+ });
519
+ pkgDir = dir;
520
+ }
521
+ if (!pkgName) {
522
+ const { name: inputName } = await inquirer__default.default.prompt({
523
+ type: "input",
524
+ name: "name",
525
+ message: "package name",
526
+ default: name
527
+ });
528
+ pkgName = inputName;
529
+ }
530
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(newJSONString, ["name"], pkgName, { formattingOptions }));
531
+ let pkgRepo = getWDPackageJSONFiled(wd, "repository");
532
+ if (typeof pkgRepo === "string") {
533
+ pkgRepo = {
534
+ type: "git",
535
+ url: pkgRepo,
536
+ directory: pkgDir
537
+ };
538
+ }
539
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
540
+ newJSONString,
541
+ ["repository"],
542
+ pkgRepo,
543
+ { formattingOptions }
544
+ ));
545
+ const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
546
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
547
+ newJSONString,
548
+ ["homepage"],
549
+ homepage,
550
+ { formattingOptions }
551
+ ));
552
+ let labels = resolvedBug.labels;
553
+ if (typeof labels === "function")
554
+ labels = labels({
555
+ name: pkgName,
556
+ dir: pkgDir
557
+ });
558
+ labels.push(`scope:${pkgName}`);
559
+ const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
560
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
561
+ newJSONString,
562
+ ["bugs"],
563
+ bugs,
564
+ { formattingOptions }
565
+ ));
566
+ function pkgDirTo(to) {
567
+ if (!pkgDir)
568
+ throw new Error("pkgDir is not defined");
569
+ return path__default.default.resolve(pkgDir, to);
570
+ }
571
+ if (!fs__default.default.existsSync(pkgDir))
572
+ fs__default.default.mkdirSync(pkgDir);
573
+ const pkgJSONFilePath = pkgDirTo("package.json");
574
+ if (fs__default.default.existsSync(pkgJSONFilePath)) {
575
+ throw new Error("package.json already exists");
576
+ }
577
+ fs__default.default.writeFileSync(pkgJSONFilePath, newJSONString);
578
+ console.log(newJSONString, "written to", pkgJSONFilePath);
579
+ const license = getWDPackageJSONFiled(wd, "license");
580
+ const readmeFilePath = pkgDirTo("README.md");
581
+ if (typeof readme === "function") {
582
+ readme = readme({
583
+ dir: pkgDir,
584
+ packageJson: JSON.parse(newJSONString)
585
+ });
586
+ }
587
+ const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
588
+ fs__default.default.writeFileSync(readmeFilePath, readmeContent);
589
+ });
590
+
182
591
  commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-p, --preview", "preview publish").action(async ({ preview, bumper: bumper$1, ...options }) => {
183
592
  actionRestore();
184
593
  const { value = {} } = await getSelectedProjectsGraph() ?? {};
@@ -230,7 +639,7 @@
230
639
  console.warn("preview mode");
231
640
  continue;
232
641
  }
233
- childProcess__namespace.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
642
+ childProcess__namespace$1.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
234
643
  cwd: dir,
235
644
  stdio: "inherit"
236
645
  });
@@ -244,53 +653,8 @@
244
653
  actionDone();
245
654
  });
246
655
 
247
- const FILE_TEMPLATE = (manifest) => `
248
- const pkg = ${JSON.stringify(manifest, null, 2)}
249
- const { jiek = {} } = pkg
250
- const templateArg = jiek.templateArgFilePath
251
- ? require.resolve(jiek.templateArgFilePath)
252
- : {
253
- styled: jiek.styled
254
- }
255
- module.exports = require('jiek/rollup').template(templateArg, pkg)
256
- `.trimStart();
257
- commander.program.command("build").action(async () => {
258
- actionRestore();
259
- const {
260
- wd,
261
- value = {}
262
- } = await getSelectedProjectsGraph() ?? {};
263
- if (Object.keys(value).length === 0) {
264
- throw new Error("no package found");
265
- }
266
- const jiekTempDir = (...paths) => path__default.default.resolve(wd, "node_modules/.jiek", ...paths);
267
- if (!fs__default.default.existsSync(jiekTempDir()))
268
- fs__default.default.mkdirSync(jiekTempDir());
269
- const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
270
- let i = 0;
271
- for (const [dir, manifest] of Object.entries(value)) {
272
- const newManifest = mergePackageJson(manifest, dir);
273
- const escapeManifestName = manifest.name?.replace(/^@/g, "").replace(/\//g, "+");
274
- const configFile = jiekTempDir(
275
- `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
276
- );
277
- fs__default.default.writeFileSync(configFile, FILE_TEMPLATE(newManifest));
278
- let prefix = "";
279
- if (process.env.NODE_ENV === "test") {
280
- const registerPath = require.resolve("esbuild-register");
281
- const loaderPath = require.resolve("esbuild-register/loader");
282
- prefix = `node --import ${registerPath} -r ${loaderPath} `;
283
- }
284
- childProcess__namespace$1.execSync(`${prefix}${rollupBinaryPath} -c ${configFile}`, {
285
- cwd: dir,
286
- stdio: "inherit"
287
- });
288
- }
289
- actionDone();
290
- });
291
-
292
656
  const pkg = require("../package.json");
293
- commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path");
657
+ commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
294
658
  commander.program.parse(process.argv);
295
659
 
296
660
  }));