jiek 0.2.0-alpha.1 → 0.2.1-alpha.1

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,395 @@
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
+ default:
320
+ throw new Error(`unsupported config file type: ${ext}`);
321
+ }
322
+ if (!module)
323
+ throw new Error("config file is empty");
324
+ return module.default ?? module;
325
+ }
326
+
327
+ const PACKAGE_JSON_TEMPLATE = `{
328
+ "name": "",
329
+ "version": "0.0.1",
330
+ "description": "",
331
+ "license": "",
332
+ "author": "",
333
+ "files": ["dist"],
334
+ "exports": {
335
+ ".": "./src/index.ts"
336
+ },
337
+ "scripts": {
338
+ },
339
+ "homepage": "",
340
+ "repository": "",
341
+ "bugs": ""
342
+ }`.trimStart();
343
+ const README_TEMPLATE = `# $name
344
+
345
+ ## Installation
346
+
347
+ \`\`\`bash
348
+ npm install $name
349
+ # or
350
+ pnpm install $name
351
+ # or
352
+ yarn add $name
353
+ \`\`\`
354
+
355
+ ## Usage
356
+
357
+
358
+ ## License
359
+
360
+ $license
361
+ `.trimStart();
362
+ function getTemplateStr(wd, template) {
363
+ let templateString = template ?? PACKAGE_JSON_TEMPLATE;
364
+ let isTemplateFile = false;
365
+ try {
366
+ if (template)
367
+ JSON.parse(template);
368
+ } catch (e) {
369
+ isTemplateFile = true;
370
+ }
371
+ if (isTemplateFile) {
372
+ const templatePath = path__default.default.resolve(wd, template);
373
+ templateString = fs__default.default.readFileSync(templatePath, "utf-8");
374
+ }
375
+ return templateString;
376
+ }
377
+ const wdCache = /* @__PURE__ */ new Map();
378
+ function getWDPackageJSONFiled(wd, field) {
379
+ if (wdCache.has(wd)) {
380
+ return wdCache.get(wd)[field];
381
+ }
382
+ const packageJSONPath = path__default.default.resolve(wd, "package.json");
383
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(packageJSONPath, "utf-8"));
384
+ wdCache.set(wd, packageJSON);
385
+ return packageJSON[field];
386
+ }
387
+ async function getName(named, name, {
388
+ wd,
389
+ cwd,
390
+ workspaceName
391
+ }) {
392
+ const relativePath = cwd.replace(`${wd}/`, "");
393
+ let basename = path__default.default.basename(cwd);
394
+ if (typeof named === "function") {
395
+ return named(name, {
396
+ full: wd,
397
+ relative: cwd
398
+ });
399
+ }
400
+ let isParentMatched = false;
401
+ let matchedKey;
402
+ let matchedRule;
403
+ if (typeof named === "object") {
404
+ const isWD = cwd === wd;
405
+ if (isWD) {
406
+ const { rule } = await inquirer__default.default.prompt({
407
+ type: "list",
408
+ name: "rule",
409
+ message: "choose a rule",
410
+ default: "default",
411
+ choices: ["default"].concat(Object.keys(named))
412
+ });
413
+ if (rule !== "default") {
414
+ matchedKey = rule;
415
+ matchedRule = named[rule];
416
+ }
417
+ } else
418
+ for (const [key, value] of Object.entries(named)) {
419
+ if (micromatch.isMatch(relativePath, key)) {
420
+ matchedKey = key;
421
+ matchedRule = value;
422
+ break;
423
+ }
424
+ if (micromatch.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
425
+ isParentMatched = true;
426
+ matchedKey = key;
427
+ matchedRule = value;
428
+ break;
429
+ }
430
+ }
431
+ }
432
+ if (!matchedRule) {
433
+ matchedKey = "packages/*";
434
+ matchedRule = `@${workspaceName}/$basename`;
435
+ }
436
+ if (!matchedRule)
437
+ throw new Error("no matched rule");
438
+ if (!name && isParentMatched) {
439
+ basename = await inquirer__default.default.prompt({
440
+ type: "input",
441
+ name: "name",
442
+ message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
443
+ `
444
+ }).then(({ name: name2 }) => name2);
445
+ }
446
+ if (typeof matchedRule === "function") {
447
+ return matchedRule(name, {
448
+ full: wd,
449
+ relative: cwd,
450
+ basename
451
+ });
452
+ }
453
+ if (typeof matchedRule === "string") {
454
+ const dirName = name ?? basename;
455
+ return [
456
+ matchedRule.replace(/\$basename/g, dirName),
457
+ matchedKey?.replace(/\/\*$/g, `/${dirName}`)
458
+ ];
459
+ }
460
+ throw new Error("no matched rule");
461
+ }
462
+ commander.program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
463
+ const [, name] = commander.program.args;
464
+ const cwd = process.cwd();
465
+ const { init = {} } = loadConfig() ?? {};
466
+ const { wd } = getWD();
467
+ const workspaceName = path__default.default.basename(wd);
468
+ const {
469
+ named,
470
+ template,
471
+ bug = {},
472
+ readme: _readme = README_TEMPLATE,
473
+ readmeTemplate
474
+ } = init;
475
+ const resolvedBug = {
476
+ template: "bug_report.yml",
477
+ labels: ["bug"],
478
+ ...bug
479
+ };
480
+ let readme = _readme;
481
+ if (readmeTemplate) {
482
+ const readmeTemplatePath = path__default.default.resolve(wd, readmeTemplate);
483
+ readme = fs__default.default.readFileSync(readmeTemplatePath, "utf-8");
484
+ }
485
+ const templateString = getTemplateStr(wd, template);
486
+ const { indent = " " } = detectIndent__default.default(templateString);
487
+ const formattingOptions = {
488
+ tabSize: indent.length,
489
+ insertSpaces: true
490
+ };
491
+ const passFields = [
492
+ "license",
493
+ "author"
494
+ ];
495
+ let newJSONString = templateString;
496
+ for (const field of passFields) {
497
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
498
+ newJSONString,
499
+ [field],
500
+ getWDPackageJSONFiled(wd, field),
501
+ { formattingOptions }
502
+ ));
503
+ }
504
+ let [pkgName, pkgDir] = await getName(named, name, {
505
+ wd,
506
+ cwd,
507
+ workspaceName
508
+ });
509
+ if (!pkgDir) {
510
+ const { dir } = await inquirer__default.default.prompt({
511
+ type: "input",
512
+ name: "dir",
513
+ message: "package directory",
514
+ default: name
515
+ });
516
+ pkgDir = dir;
517
+ }
518
+ if (!pkgName) {
519
+ const { name: inputName } = await inquirer__default.default.prompt({
520
+ type: "input",
521
+ name: "name",
522
+ message: "package name",
523
+ default: name
524
+ });
525
+ pkgName = inputName;
526
+ }
527
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(newJSONString, ["name"], pkgName, { formattingOptions }));
528
+ let pkgRepo = getWDPackageJSONFiled(wd, "repository");
529
+ if (typeof pkgRepo === "string") {
530
+ pkgRepo = {
531
+ type: "git",
532
+ url: pkgRepo,
533
+ directory: pkgDir
534
+ };
535
+ }
536
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
537
+ newJSONString,
538
+ ["repository"],
539
+ pkgRepo,
540
+ { formattingOptions }
541
+ ));
542
+ const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
543
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
544
+ newJSONString,
545
+ ["homepage"],
546
+ homepage,
547
+ { formattingOptions }
548
+ ));
549
+ let labels = resolvedBug.labels;
550
+ if (typeof labels === "function")
551
+ labels = labels({
552
+ name: pkgName,
553
+ dir: pkgDir
554
+ });
555
+ labels.push(`scope:${pkgName}`);
556
+ const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
557
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
558
+ newJSONString,
559
+ ["bugs"],
560
+ bugs,
561
+ { formattingOptions }
562
+ ));
563
+ function pkgDirTo(to) {
564
+ if (!pkgDir)
565
+ throw new Error("pkgDir is not defined");
566
+ return path__default.default.resolve(pkgDir, to);
567
+ }
568
+ if (!fs__default.default.existsSync(pkgDir))
569
+ fs__default.default.mkdirSync(pkgDir);
570
+ const pkgJSONFilePath = pkgDirTo("package.json");
571
+ if (fs__default.default.existsSync(pkgJSONFilePath)) {
572
+ throw new Error("package.json already exists");
573
+ }
574
+ fs__default.default.writeFileSync(pkgJSONFilePath, newJSONString);
575
+ console.log(newJSONString, "written to", pkgJSONFilePath);
576
+ const license = getWDPackageJSONFiled(wd, "license");
577
+ const readmeFilePath = pkgDirTo("README.md");
578
+ if (typeof readme === "function") {
579
+ readme = readme({
580
+ dir: pkgDir,
581
+ packageJson: JSON.parse(newJSONString)
582
+ });
583
+ }
584
+ const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
585
+ fs__default.default.writeFileSync(readmeFilePath, readmeContent);
586
+ });
587
+
182
588
  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
589
  actionRestore();
184
590
  const { value = {} } = await getSelectedProjectsGraph() ?? {};
@@ -230,7 +636,7 @@
230
636
  console.warn("preview mode");
231
637
  continue;
232
638
  }
233
- childProcess__namespace.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
639
+ childProcess__namespace$1.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
234
640
  cwd: dir,
235
641
  stdio: "inherit"
236
642
  });
@@ -244,53 +650,8 @@
244
650
  actionDone();
245
651
  });
246
652
 
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
653
  const pkg = require("../package.json");
293
- commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path");
654
+ commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
294
655
  commander.program.parse(process.argv);
295
656
 
296
657
  }));