@tiddlywiki/mws 0.0.15 → 0.0.17

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 (43) hide show
  1. package/README.md +21 -34
  2. package/dist/server.d.ts +20 -9
  3. package/dist/server.js +3920 -379
  4. package/dist/server.js.map +1 -1
  5. package/editions/mws-docs/tiddlers/$__StoryList.tid +1 -3
  6. package/editions/mws-docs/tiddlers/2025-02-18 - User Management.md +56 -0
  7. package/editions/mws-docs/tiddlers/2025-02-18 - User Management.md.meta +5 -0
  8. package/editions/mws-docs/tiddlers/2025-04-03 - Phases of Development.md +64 -0
  9. package/editions/mws-docs/tiddlers/2025-04-03 - Phases of Development.md.meta +5 -0
  10. package/editions/mws-docs/tiddlers/2025-04-13 - Plugins.md +18 -0
  11. package/editions/mws-docs/tiddlers/2025-04-13 - Plugins.md.meta +5 -0
  12. package/editions/mws-docs/tiddlers/2025-05-04.md +13 -0
  13. package/editions/mws-docs/tiddlers/2025-05-04.md.meta +5 -0
  14. package/editions/mws-docs/tiddlers/2025-05-06.md +19 -0
  15. package/editions/mws-docs/tiddlers/2025-05-06.md.meta +5 -0
  16. package/editions/mws-docs/tiddlers/Access Control.md +17 -0
  17. package/editions/mws-docs/tiddlers/Access Control.md.meta +5 -0
  18. package/editions/mws-docs/tiddlers/Application Access & Security.md +98 -0
  19. package/editions/mws-docs/tiddlers/Application Access & Security.md.meta +5 -0
  20. package/editions/mws-docs/tiddlers/Checklists and Features.md +15 -0
  21. package/editions/mws-docs/tiddlers/Checklists and Features.md.meta +5 -0
  22. package/editions/mws-docs/tiddlers/HTTP API.md +17 -0
  23. package/editions/mws-docs/tiddlers/HTTP API.md.meta +5 -0
  24. package/editions/mws-docs/tiddlers/Installation.tid +11 -2
  25. package/editions/mws-docs/tiddlers/MWS Architecture.md +15 -0
  26. package/editions/mws-docs/tiddlers/MWS Architecture.md.meta +5 -0
  27. package/editions/mws-docs/tiddlers/Moduler Design.md +5 -0
  28. package/editions/mws-docs/tiddlers/Moduler Design.md.meta +1 -1
  29. package/editions/mws-docs/tiddlers/Notes.tid +5 -0
  30. package/editions/mws-docs/tiddlers/Reference.md +0 -149
  31. package/editions/mws-docs/tiddlers/Reference.md.meta +4 -1
  32. package/editions/mws-docs/tiddlers/Usage.tid +3 -3
  33. package/editions/mws-docs/tiddlers/system/$__palettes_MUI-Dark +173 -0
  34. package/editions/mws-docs/tiddlers/system/$__palettes_MUI-Dark.meta +6 -0
  35. package/editions/mws-docs/tiddlers/system/$__palettes_MUI-Light +172 -0
  36. package/editions/mws-docs/tiddlers/system/$__palettes_MUI-Light.meta +6 -0
  37. package/package.json +11 -20
  38. package/plugins/client/tiddlers/readme.tid +0 -3
  39. package/react-user-mgmt/public/main.js +32 -32
  40. package/react-user-mgmt/public/main.js.map +4 -4
  41. package/react-user-mgmt/public/stats.json +1 -1
  42. package/scripts.mjs +34 -0
  43. package/.env-cmdrc +0 -5
package/dist/server.js CHANGED
@@ -11660,7 +11660,7 @@ var init_data_checks = __esm({
11660
11660
  // allow unowned for any user (conditional for anon reads)
11661
11661
  (user_id || allowAnon) && { acl: { none: {} }, owner_id: null },
11662
11662
  // allow owner for user
11663
- user_id && { owner_id: user_id },
11663
+ user_id && { owner_id: { equals: user_id, not: null } },
11664
11664
  // allow acl for user
11665
11665
  user_id && role_ids?.length && {
11666
11666
  acl: {
@@ -12154,12 +12154,12 @@ var init_StateObject = __esm({
12154
12154
  init_streamer();
12155
12155
  init_utils2();
12156
12156
  _StateObject = class _StateObject extends StreamerState {
12157
- constructor(streamer, routePath, bodyFormat, user, commander, tiddlerCache) {
12157
+ constructor(streamer, routePath, bodyFormat, user, router, tiddlerCache) {
12158
12158
  super(streamer);
12159
12159
  this.routePath = routePath;
12160
12160
  this.bodyFormat = bodyFormat;
12161
12161
  this.user = user;
12162
- this.commander = commander;
12162
+ this.router = router;
12163
12163
  this.tiddlerCache = tiddlerCache;
12164
12164
  this.z = z3;
12165
12165
  this.STREAM_ENDED = STREAM_ENDED;
@@ -12170,9 +12170,9 @@ var init_StateObject = __esm({
12170
12170
  this.$transaction = /* @__PURE__ */ __name(async (fn) => {
12171
12171
  return await this.engine.$transaction((prisma) => fn(prisma));
12172
12172
  }, "$transaction");
12173
- this.engine = commander.engine;
12174
- this.config = commander.siteConfig;
12175
- this.PasswordService = commander.PasswordService;
12173
+ this.engine = router.engine;
12174
+ this.config = router.siteConfig;
12175
+ this.PasswordService = router.PasswordService;
12176
12176
  this.readMultipartData = readMultipartData.bind(this);
12177
12177
  this.sendResponse = sendResponse.bind(void 0, this.config, this);
12178
12178
  this.pathParams = Object.fromEntries(routePath.map(
@@ -12222,7 +12222,7 @@ var init_StateObject = __esm({
12222
12222
  * - **308 Permanent Redirect:** The resource has permanently moved; the client should use the new URL in future requests.
12223
12223
  */
12224
12224
  redirect(location, pushLocation) {
12225
- return this.sendEmpty(302, { "Location": location });
12225
+ return this.sendEmpty(302, { "Location": this.config.pathPrefix + location });
12226
12226
  }
12227
12227
  sendSSE(retryMilliseconds) {
12228
12228
  if (retryMilliseconds !== void 0) {
@@ -12414,7 +12414,12 @@ var init_manager_recipes = __esm({
12414
12414
  }
12415
12415
  }
12416
12416
  },
12417
- where: isAdmin ? void 0 : { recipe_bags: { every: { bag: { OR } } } }
12417
+ where: isAdmin ? void 0 : {
12418
+ OR: [
12419
+ { recipe_bags: { every: { bag: { OR } } } },
12420
+ { owner_id: { equals: user_id, not: null } }
12421
+ ]
12422
+ }
12418
12423
  });
12419
12424
  const userListUser = !isAdmin && await prisma.users.findMany({
12420
12425
  select: { user_id: true, username: true }
@@ -12601,7 +12606,7 @@ var init_manager_recipes = __esm({
12601
12606
  const existing = await prisma.recipes.findUnique({ where: { recipe_name } });
12602
12607
  this.assertCreateOrUpdate({ user, type: "recipe", isCreate, owner_id, existing });
12603
12608
  const { isAdmin, user_id } = user;
12604
- const OR = this.checks.getWhereACL({ permission: "ADMIN", user_id });
12609
+ const OR = isAdmin ? void 0 : this.checks.getWhereACL({ permission: "ADMIN", user_id });
12605
12610
  const bags = new Map(
12606
12611
  await prisma.bags.findMany({
12607
12612
  where: { bag_name: { in: bag_names.map((e) => e.bag_name) } }
@@ -12609,14 +12614,12 @@ var init_manager_recipes = __esm({
12609
12614
  );
12610
12615
  const missing = bag_names.filter((e) => !bags.has(e.bag_name));
12611
12616
  if (missing.length) throw "Some bags not found: " + JSON.stringify(missing);
12612
- const bagsAcl = new Map(
12613
- await prisma.bags.findMany({
12614
- where: { bag_name: { in: bag_names.map((e) => e.bag_name) }, OR }
12615
- }).then((bags2) => bags2.map((bag) => [bag.bag_name, bag]))
12616
- );
12617
+ const bagsAcl = new Map((await prisma.bags.findMany({
12618
+ where: { bag_name: { in: bag_names.map((e) => e.bag_name) }, OR }
12619
+ })).map((bag) => [bag.bag_name, bag]));
12617
12620
  const createBags = bag_names.map((bag, position) => ({
12618
12621
  bag_id: bags.get(bag.bag_name).bag_id,
12619
- with_acl: bagsAcl && bagsAcl.has(bag.bag_name) && bag.with_acl,
12622
+ with_acl: bagsAcl.has(bag.bag_name) && bag.with_acl,
12620
12623
  position
12621
12624
  }));
12622
12625
  if (existing) {
@@ -12914,13 +12917,20 @@ var init_TiddlerStore = __esm({
12914
12917
  init_esm_shims();
12915
12918
  init_utils2();
12916
12919
  _TiddlerStore = class _TiddlerStore {
12917
- constructor(commander, prisma) {
12918
- this.commander = commander;
12920
+ constructor(fieldModules, attachService, siteConfig, prisma) {
12921
+ this.fieldModules = fieldModules;
12922
+ this.attachService = attachService;
12923
+ this.siteConfig = siteConfig;
12919
12924
  this.prisma = prisma;
12920
- this.fieldModules = this.commander.$tw.Tiddler.fieldModules;
12921
- this.attachService = new commander.AttachmentService(commander.siteConfig, prisma);
12922
- this.storePath = commander.siteConfig.storePath;
12923
- this.config = commander.siteConfig;
12925
+ this.storePath = this.siteConfig.storePath;
12926
+ }
12927
+ static fromCommander(commander2, prisma) {
12928
+ return new _TiddlerStore(
12929
+ commander2.$tw.Tiddler.fieldModules,
12930
+ new commander2.AttachmentService(commander2.siteConfig, prisma),
12931
+ commander2.siteConfig,
12932
+ prisma
12933
+ );
12924
12934
  }
12925
12935
  /*
12926
12936
  Returns null if a bag/recipe name is valid, or a string error message if not
@@ -13170,7 +13180,7 @@ var init_TiddlerStore = __esm({
13170
13180
  const stream = new Readable();
13171
13181
  stream._read = () => {
13172
13182
  const type = tiddlerInfo.tiddler.type || "text/plain";
13173
- stream.push(tiddlerInfo.tiddler.text || "", (this.config.contentTypeInfo[type] || { encoding: "utf8" }).encoding);
13183
+ stream.push(tiddlerInfo.tiddler.text || "", (this.siteConfig.contentTypeInfo[type] || { encoding: "utf8" }).encoding);
13174
13184
  stream.push(null);
13175
13185
  };
13176
13186
  return {
@@ -14093,10 +14103,16 @@ var init_bag_file_server = __esm({
14093
14103
  import_sjcl = __toESM(require_sjcl(), 1);
14094
14104
  _TiddlerServer = class _TiddlerServer extends TiddlerStore {
14095
14105
  constructor(state, prisma) {
14096
- super(state.commander, prisma);
14106
+ const router = state.router;
14107
+ super(
14108
+ router.fieldModules,
14109
+ new router.AttachmentService(router.siteConfig, prisma),
14110
+ router.siteConfig,
14111
+ prisma
14112
+ );
14097
14113
  this.state = state;
14098
14114
  }
14099
- toTiddlyWebJson(info11) {
14115
+ toTiddlyWebJson(info12) {
14100
14116
  const output = { fields: {} };
14101
14117
  const knownFields = [
14102
14118
  "bag",
@@ -14113,16 +14129,16 @@ var init_bag_file_server = __esm({
14113
14129
  "type",
14114
14130
  "uri"
14115
14131
  ];
14116
- each(info11.tiddler, (field, name) => {
14132
+ each(info12.tiddler, (field, name) => {
14117
14133
  if (knownFields.indexOf(name) !== -1) {
14118
14134
  output[name] = field;
14119
14135
  } else {
14120
14136
  output.fields[name] = field;
14121
14137
  }
14122
14138
  });
14123
- output.type = info11.tiddler.type || "text/vnd.tiddlywiki";
14124
- output.revision = `${info11.tiddler_id}`;
14125
- output.bag = info11.bag_name;
14139
+ output.type = info12.tiddler.type || "text/vnd.tiddlywiki";
14140
+ output.revision = `${info12.tiddler_id}`;
14141
+ output.bag = info12.bag_name;
14126
14142
  return output;
14127
14143
  }
14128
14144
  /** If neither bag_name nor bag_id are specified, the fallback will be sent. */
@@ -14611,6 +14627,62 @@ var init_router_tiddlers = __esm({
14611
14627
  }
14612
14628
  });
14613
14629
 
14630
+ // src/routes/tw-test.ts
14631
+ import { TiddlyWiki } from "tiddlywiki";
14632
+ function DocsRoute(parent, config) {
14633
+ const wikiRouter = new TWRouter(config);
14634
+ parent.defineRoute({
14635
+ method: ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE"],
14636
+ bodyFormat: "stream",
14637
+ path: /^\/mws(\/|$)/,
14638
+ pathParams: []
14639
+ }, async (state) => {
14640
+ if (state.urlInfo.pathname === "/mws") throw state.redirect("/mws/");
14641
+ const { req, res } = state.streamer;
14642
+ if (req.url === "/mws") req.url = "/mws/";
14643
+ wikiRouter.twserver.requestHandler(req, res, {});
14644
+ return new Promise((r, c) => res.on("finish", r).on("error", c));
14645
+ });
14646
+ }
14647
+ var _TWRouter, TWRouter;
14648
+ var init_tw_test = __esm({
14649
+ "src/routes/tw-test.ts"() {
14650
+ "use strict";
14651
+ init_esm_shims();
14652
+ __name(DocsRoute, "DocsRoute");
14653
+ _TWRouter = class _TWRouter {
14654
+ constructor(config) {
14655
+ this.config = config;
14656
+ this.$tw = TiddlyWiki();
14657
+ this.$tw.boot.argv = [
14658
+ "+plugins/tiddlywiki/tiddlyweb",
14659
+ "+plugins/tiddlywiki/filesystem",
14660
+ "./editions/mws-docs"
14661
+ ];
14662
+ this.$tw.preloadTiddler({
14663
+ text: "$protocol$//$host$" + this.config.pathPrefix + "/mws/",
14664
+ title: "$:/config/tiddlyweb/host"
14665
+ });
14666
+ this.$tw.boot.boot(() => {
14667
+ const Server2 = this.$tw.modules.execute("$:/core/modules/server/server.js", "tw-test.ts").Server;
14668
+ this.twserver = new Server2({
14669
+ wiki: this.$tw.wiki,
14670
+ variables: {
14671
+ // do not use a trailing slash
14672
+ "path-prefix": this.config.pathPrefix + "/mws",
14673
+ "root-tiddler": "$:/core/save/all"
14674
+ },
14675
+ routes: []
14676
+ });
14677
+ this.$tw.hooks.invokeHook("th-server-command-post-start", this.twserver, null, "mws");
14678
+ });
14679
+ }
14680
+ };
14681
+ __name(_TWRouter, "TWRouter");
14682
+ TWRouter = _TWRouter;
14683
+ }
14684
+ });
14685
+
14614
14686
  // import("./**/*/**/*") in src/routes/index.ts
14615
14687
  var globImport;
14616
14688
  var init_ = __esm({
@@ -14627,9 +14699,10 @@ var init_ = __esm({
14627
14699
  // src/routes/index.ts
14628
14700
  import { Prisma } from "@prisma/client";
14629
14701
  async function RootRoute(root, config) {
14702
+ if (process.env.ENABLE_DOCS_ROUTE) DocsRoute(root, config);
14630
14703
  TiddlerRouter.defineRoutes(root);
14631
14704
  ManagerRoutes(root, config);
14632
- if (typeof ENABLE_UNSAFE_PRISMA_ROUTE !== "undefined")
14705
+ if (process.env.ENABLE_UNSAFE_PRISMA_ROUTE)
14633
14706
  root.defineRoute({
14634
14707
  method: ["POST"],
14635
14708
  path: /^\/prisma$/,
@@ -14686,6 +14759,7 @@ var init_routes = __esm({
14686
14759
  init_utils2();
14687
14760
  init_managers();
14688
14761
  init_router_tiddlers();
14762
+ init_tw_test();
14689
14763
  init_();
14690
14764
  __name(RootRoute, "RootRoute");
14691
14765
  __name(importEsbuild, "importEsbuild");
@@ -14779,7 +14853,7 @@ async function setupDevServer(enableDevServer, pathPrefix) {
14779
14853
  }, index_file), "sendIndex");
14780
14854
  if (state.url === "/") return sendIndex();
14781
14855
  return state.sendFile(200, {}, {
14782
- root: rootdir,
14856
+ root: resolve3(rootdir, "public"),
14783
14857
  reqpath: state.url,
14784
14858
  on404: /* @__PURE__ */ __name(async () => sendIndex(), "on404")
14785
14859
  });
@@ -14870,8 +14944,8 @@ var init_setupDevServer = __esm({
14870
14944
 
14871
14945
  // src/routes/cache.ts
14872
14946
  import { ok as ok4 } from "assert";
14873
- async function startupCache(commander) {
14874
- const $tw2 = commander.$tw;
14947
+ async function startupCache(commander2) {
14948
+ const $tw2 = commander2.$tw;
14875
14949
  const bootTiddlers = $tw2.loadTiddlersFromPath($tw2.boot.bootPath).flatMap((file) => file.tiddlers);
14876
14950
  const coreTiddler = $tw2.loadPluginFolder($tw2.boot.corePath);
14877
14951
  ok4(coreTiddler);
@@ -14958,20 +15032,21 @@ var init_router = __esm({
14958
15032
  }
14959
15033
  }, "zodTransformJSON");
14960
15034
  _Router = class _Router {
14961
- constructor(rootRoute2, commander, tiddlerCache) {
15035
+ constructor(rootRoute2, commander2, tiddlerCache) {
14962
15036
  this.rootRoute = rootRoute2;
14963
- this.commander = commander;
14964
15037
  this.tiddlerCache = tiddlerCache;
14965
- this.pathPrefix = "";
14966
15038
  this.enableBrowserCache = true;
14967
15039
  this.enableGzip = false;
14968
15040
  this.csrfDisable = false;
14969
- this.engine = commander.engine;
14970
- this.SessionManager = commander.SessionManager;
14971
- this.pathPrefix = commander.siteConfig.pathPrefix;
14972
- }
14973
- static async makeRouter(commander, enableDevServer) {
14974
- const sendDevServer = await setupDevServer(enableDevServer, commander.siteConfig.pathPrefix);
15041
+ this.engine = commander2.engine;
15042
+ this.SessionManager = commander2.SessionManager;
15043
+ this.siteConfig = commander2.siteConfig;
15044
+ this.PasswordService = commander2.PasswordService;
15045
+ this.fieldModules = commander2.$tw.Tiddler.fieldModules;
15046
+ this.AttachmentService = commander2.AttachmentService;
15047
+ }
15048
+ static async makeRouter(commander2, enableDevServer) {
15049
+ const sendDevServer = await setupDevServer(enableDevServer, commander2.siteConfig.pathPrefix);
14975
15050
  const rootRoute2 = defineRoute(ROOT_ROUTE, {
14976
15051
  method: AllowedMethods,
14977
15052
  path: /^/,
@@ -14979,10 +15054,13 @@ var init_router = __esm({
14979
15054
  }, async (state) => {
14980
15055
  state.sendDevServer = sendDevServer.bind(void 0, state);
14981
15056
  });
14982
- await commander.SessionManager.defineRoutes(rootRoute2);
14983
- await RootRoute(rootRoute2, commander.siteConfig);
14984
- const cache = await startupCache(commander);
14985
- return new _Router(rootRoute2, commander, cache);
15057
+ await commander2.SessionManager.defineRoutes(rootRoute2);
15058
+ await RootRoute(rootRoute2, commander2.siteConfig);
15059
+ const cache = await startupCache(commander2);
15060
+ return new _Router(rootRoute2, commander2, cache);
15061
+ }
15062
+ get pathPrefix() {
15063
+ return this.siteConfig.pathPrefix;
14986
15064
  }
14987
15065
  handleIncomingRequest(req, res) {
14988
15066
  const [ok8, err, streamer] = function() {
@@ -15019,7 +15097,7 @@ var init_router = __esm({
15019
15097
  routePath,
15020
15098
  bodyFormat,
15021
15099
  authUser,
15022
- this.commander,
15100
+ this,
15023
15101
  this.tiddlerCache
15024
15102
  )
15025
15103
  );
@@ -15162,10 +15240,10 @@ var init_router = __esm({
15162
15240
  });
15163
15241
 
15164
15242
  // src/tiddlywiki.ts
15165
- import { TiddlyWiki } from "tiddlywiki";
15243
+ import { TiddlyWiki as TiddlyWiki2 } from "tiddlywiki";
15166
15244
  import { ok as ok5 } from "node:assert";
15167
15245
  async function bootTiddlyWiki(wikiPath) {
15168
- const $tw2 = TiddlyWiki();
15246
+ const $tw2 = TiddlyWiki2();
15169
15247
  $tw2.utils.eachAsync = eachAsync;
15170
15248
  $tw2.boot.boot = async (callback) => {
15171
15249
  $tw2.crypto = new $tw2.utils.Crypto();
@@ -15197,22 +15275,14 @@ async function bootTiddlyWiki(wikiPath) {
15197
15275
  startup: /* @__PURE__ */ __name(() => {
15198
15276
  }, "startup")
15199
15277
  });
15200
- $tw2.preloadTiddler({ title: "$:/plugins/tiddlywiki/multiwikiserver/startup.js" });
15201
- $tw2.modules.define("$:/plugins/tiddlywiki/multiwikiserver/startup.js", "startup", {
15202
- name: "multiwikiserver",
15203
- platforms: ["node"],
15204
- after: ["load-modules"],
15205
- before: ["story", "commands"],
15206
- synchronous: true,
15207
- startup: /* @__PURE__ */ __name(() => {
15208
- }, "startup")
15209
- });
15210
15278
  $tw2.boot.argv = [
15211
15279
  "++" + dist_resolve("../plugins/client"),
15212
15280
  "+plugins/tiddlywiki/tiddlyweb",
15281
+ // these are sane defaults, these should be in the recipe
15213
15282
  "+themes/tiddlywiki/vanilla",
15214
15283
  "+themes/tiddlywiki/snowwhite",
15215
15284
  wikiPath
15285
+ // this should be inert
15216
15286
  ];
15217
15287
  await new Promise((resolve13) => $tw2.boot.boot(resolve13));
15218
15288
  ok5(!$tw2.boot.tasks.readBrowserTiddlers);
@@ -15554,231 +15624,3603 @@ var init_attachments = __esm({
15554
15624
  }
15555
15625
  });
15556
15626
 
15557
- // src/commands/mws-load-plugin-bags.ts
15558
- var mws_load_plugin_bags_exports = {};
15559
- __export(mws_load_plugin_bags_exports, {
15560
- Command: () => Command,
15561
- info: () => info
15562
- });
15563
- import { resolve as resolve5 } from "node:path";
15564
- async function loadPluginBags($tw2, store, engine) {
15565
- function makePluginBagName2(type, publisher, name) {
15566
- return "$:/" + type + "/" + (publisher ? publisher + "/" : "") + name;
15567
- }
15568
- __name(makePluginBagName2, "makePluginBagName");
15569
- function savePlugin(pluginFields, type, publisher, name) {
15570
- const bagName = makePluginBagName2(type, publisher, name);
15571
- const description = pluginFields.description ?? "(no description)";
15572
- const is_plugin = true;
15573
- return [
15574
- store.upsertBag_PrismaPromise(bagName, description, is_plugin, { allowPrivilegedCharacters: true }),
15575
- ...store.saveBagTiddlerFields_PrismaArray(pluginFields, bagName, null)
15576
- // ...Object.values(tiddlers).flatMap((fields) => store.saveBagTiddlerFields_PrismaArray(fields, bagName, null))
15577
- ].filter(truthy);
15578
- }
15579
- __name(savePlugin, "savePlugin");
15580
- function collectPlugins(folder, type, publisher) {
15581
- var pluginFolders = $tw2.utils.getSubdirectories(folder) || [];
15582
- const prismaPromiseArray2 = [];
15583
- for (var p = 0; p < pluginFolders.length; p++) {
15584
- const pluginFolderName = pluginFolders[p];
15585
- if ($tw2.boot.excludeRegExp.test(pluginFolderName)) continue;
15586
- const pluginFields = $tw2.loadPluginFolder(resolve5(folder, pluginFolderName));
15587
- if (!pluginFields?.title) continue;
15588
- prismaPromiseArray2.push(...savePlugin(pluginFields, type, publisher, pluginFolderName));
15589
- }
15590
- prismaPromiseArray2.forEach((e) => {
15591
- if (e[Symbol.toStringTag] !== "PrismaPromise") console.log(e);
15592
- });
15593
- return prismaPromiseArray2;
15594
- }
15595
- __name(collectPlugins, "collectPlugins");
15596
- function collectPublisherPlugins(folder, type) {
15597
- var publisherFolders = $tw2.utils.getSubdirectories(folder) || [];
15598
- return publisherFolders.flatMap((publisherFolderName) => {
15599
- if ($tw2.boot.excludeRegExp.test(publisherFolderName)) return [];
15600
- return collectPlugins(resolve5(folder, publisherFolderName), type, publisherFolderName);
15601
- });
15602
- }
15603
- __name(collectPublisherPlugins, "collectPublisherPlugins");
15604
- ;
15605
- const plugins = $tw2.getLibraryItemSearchPaths($tw2.config.pluginsPath, $tw2.config.pluginsEnvVar);
15606
- const themes = $tw2.getLibraryItemSearchPaths($tw2.config.themesPath, $tw2.config.themesEnvVar);
15607
- const languages = $tw2.getLibraryItemSearchPaths($tw2.config.languagesPath, $tw2.config.languagesEnvVar);
15608
- const prismaPromiseArray = [
15609
- ...plugins.flatMap((folder) => collectPublisherPlugins(folder, "plugins")),
15610
- ...themes.flatMap((folder) => collectPublisherPlugins(folder, "themes")),
15611
- ...languages.flatMap((folder) => collectPlugins(folder, "languages"))
15612
- ];
15613
- prismaPromiseArray.forEach((e) => {
15614
- if (e[Symbol.toStringTag] !== "PrismaPromise") {
15615
- if (Array.isArray(e)) console.log(e.length);
15616
- else console.log(e);
15617
- }
15618
- });
15619
- await engine.$transaction(prismaPromiseArray);
15620
- }
15621
- var info, _Command, Command;
15622
- var init_mws_load_plugin_bags = __esm({
15623
- "src/commands/mws-load-plugin-bags.ts"() {
15627
+ // node_modules/commander/lib/error.js
15628
+ var require_error = __commonJS({
15629
+ "node_modules/commander/lib/error.js"(exports) {
15624
15630
  "use strict";
15625
15631
  init_esm_shims();
15626
- init_TiddlerStore();
15627
- init_utils2();
15628
- info = {
15629
- name: "mws-load-plugin-bags",
15630
- synchronous: true
15631
- };
15632
- _Command = class _Command {
15633
- constructor(params, commander, callback) {
15634
- this.params = params;
15635
- this.commander = commander;
15636
- this.callback = callback;
15637
- }
15638
- get $tw() {
15639
- return this.commander.$tw;
15632
+ var _CommanderError = class _CommanderError extends Error {
15633
+ /**
15634
+ * Constructs the CommanderError class
15635
+ * @param {number} exitCode suggested exit code which could be used with process.exit
15636
+ * @param {string} code an id string representing the error
15637
+ * @param {string} message human-readable description of the error
15638
+ */
15639
+ constructor(exitCode, code, message) {
15640
+ super(message);
15641
+ Error.captureStackTrace(this, this.constructor);
15642
+ this.name = this.constructor.name;
15643
+ this.code = code;
15644
+ this.exitCode = exitCode;
15645
+ this.nestedError = void 0;
15640
15646
  }
15641
- async execute() {
15642
- console.time(`${info.name} complete`);
15643
- await loadPluginBags(
15644
- this.$tw,
15645
- new TiddlerStore(this.commander, this.commander.engine),
15646
- this.commander.engine
15647
- );
15648
- console.timeEnd(`${info.name} complete`);
15647
+ };
15648
+ __name(_CommanderError, "CommanderError");
15649
+ var CommanderError2 = _CommanderError;
15650
+ var _InvalidArgumentError = class _InvalidArgumentError extends CommanderError2 {
15651
+ /**
15652
+ * Constructs the InvalidArgumentError class
15653
+ * @param {string} [message] explanation of why argument is invalid
15654
+ */
15655
+ constructor(message) {
15656
+ super(1, "commander.invalidArgument", message);
15657
+ Error.captureStackTrace(this, this.constructor);
15658
+ this.name = this.constructor.name;
15649
15659
  }
15650
15660
  };
15651
- __name(_Command, "Command");
15652
- Command = _Command;
15653
- __name(loadPluginBags, "loadPluginBags");
15661
+ __name(_InvalidArgumentError, "InvalidArgumentError");
15662
+ var InvalidArgumentError2 = _InvalidArgumentError;
15663
+ exports.CommanderError = CommanderError2;
15664
+ exports.InvalidArgumentError = InvalidArgumentError2;
15654
15665
  }
15655
15666
  });
15656
15667
 
15657
- // src/commands/mws-render-tiddlywiki5.ts
15658
- var mws_render_tiddlywiki5_exports = {};
15659
- __export(mws_render_tiddlywiki5_exports, {
15660
- Command: () => Command2,
15661
- info: () => info2
15662
- });
15663
- import { resolve as resolve6 } from "node:path";
15664
- var writeFileSync3, info2, _Command2, Command2;
15665
- var init_mws_render_tiddlywiki5 = __esm({
15666
- "src/commands/mws-render-tiddlywiki5.ts"() {
15668
+ // node_modules/commander/lib/argument.js
15669
+ var require_argument = __commonJS({
15670
+ "node_modules/commander/lib/argument.js"(exports) {
15667
15671
  "use strict";
15668
15672
  init_esm_shims();
15669
- ({ writeFileSync: writeFileSync3 } = __require("fs"));
15670
- info2 = {
15671
- name: "mws-render-tiddlywiki5",
15672
- synchronous: true
15673
- };
15674
- _Command2 = class _Command2 {
15675
- constructor(params, commander, callback) {
15676
- this.params = params;
15677
- this.commander = commander;
15678
- this.callback = callback;
15673
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
15674
+ var _Argument = class _Argument {
15675
+ /**
15676
+ * Initialize a new command argument with the given name and description.
15677
+ * The default is that the argument is required, and you can explicitly
15678
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
15679
+ *
15680
+ * @param {string} name
15681
+ * @param {string} [description]
15682
+ */
15683
+ constructor(name, description) {
15684
+ this.description = description || "";
15685
+ this.variadic = false;
15686
+ this.parseArg = void 0;
15687
+ this.defaultValue = void 0;
15688
+ this.defaultValueDescription = void 0;
15689
+ this.argChoices = void 0;
15690
+ switch (name[0]) {
15691
+ case "<":
15692
+ this.required = true;
15693
+ this._name = name.slice(1, -1);
15694
+ break;
15695
+ case "[":
15696
+ this.required = false;
15697
+ this._name = name.slice(1, -1);
15698
+ break;
15699
+ default:
15700
+ this.required = true;
15701
+ this._name = name;
15702
+ break;
15703
+ }
15704
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
15705
+ this.variadic = true;
15706
+ this._name = this._name.slice(0, -3);
15707
+ }
15679
15708
  }
15680
- async execute() {
15681
- const result = this.commander.$tw.wiki.renderTiddler("text/plain", "$:/core/templates/tiddlywiki5.html", {
15682
- variables: {
15683
- saveTiddlerFilter: `
15684
- $:/boot/boot.css
15685
- $:/boot/boot.js
15686
- $:/boot/bootprefix.js
15687
- $:/core
15688
- $:/library/sjcl.js
15689
- $:/plugins/tiddlywiki/tiddlyweb
15690
- $:/plugins/tiddlywiki/multiwikiclient
15691
- $:/themes/tiddlywiki/snowwhite
15692
- $:/themes/tiddlywiki/vanilla
15693
- `
15709
+ /**
15710
+ * Return argument name.
15711
+ *
15712
+ * @return {string}
15713
+ */
15714
+ name() {
15715
+ return this._name;
15716
+ }
15717
+ /**
15718
+ * @package
15719
+ */
15720
+ _concatValue(value, previous) {
15721
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
15722
+ return [value];
15723
+ }
15724
+ return previous.concat(value);
15725
+ }
15726
+ /**
15727
+ * Set the default value, and optionally supply the description to be displayed in the help.
15728
+ *
15729
+ * @param {*} value
15730
+ * @param {string} [description]
15731
+ * @return {Argument}
15732
+ */
15733
+ default(value, description) {
15734
+ this.defaultValue = value;
15735
+ this.defaultValueDescription = description;
15736
+ return this;
15737
+ }
15738
+ /**
15739
+ * Set the custom handler for processing CLI command arguments into argument values.
15740
+ *
15741
+ * @param {Function} [fn]
15742
+ * @return {Argument}
15743
+ */
15744
+ argParser(fn) {
15745
+ this.parseArg = fn;
15746
+ return this;
15747
+ }
15748
+ /**
15749
+ * Only allow argument value to be one of choices.
15750
+ *
15751
+ * @param {string[]} values
15752
+ * @return {Argument}
15753
+ */
15754
+ choices(values) {
15755
+ this.argChoices = values.slice();
15756
+ this.parseArg = (arg, previous) => {
15757
+ if (!this.argChoices.includes(arg)) {
15758
+ throw new InvalidArgumentError2(
15759
+ `Allowed choices are ${this.argChoices.join(", ")}.`
15760
+ );
15694
15761
  }
15695
- });
15696
- const filepath = resolve6(this.commander.wikiPath, "tiddlywiki5.html");
15697
- writeFileSync3(filepath, result);
15762
+ if (this.variadic) {
15763
+ return this._concatValue(arg, previous);
15764
+ }
15765
+ return arg;
15766
+ };
15767
+ return this;
15768
+ }
15769
+ /**
15770
+ * Make argument required.
15771
+ *
15772
+ * @returns {Argument}
15773
+ */
15774
+ argRequired() {
15775
+ this.required = true;
15776
+ return this;
15777
+ }
15778
+ /**
15779
+ * Make argument optional.
15780
+ *
15781
+ * @returns {Argument}
15782
+ */
15783
+ argOptional() {
15784
+ this.required = false;
15785
+ return this;
15698
15786
  }
15699
15787
  };
15700
- __name(_Command2, "Command");
15701
- Command2 = _Command2;
15788
+ __name(_Argument, "Argument");
15789
+ var Argument2 = _Argument;
15790
+ function humanReadableArgName(arg) {
15791
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
15792
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
15793
+ }
15794
+ __name(humanReadableArgName, "humanReadableArgName");
15795
+ exports.Argument = Argument2;
15796
+ exports.humanReadableArgName = humanReadableArgName;
15702
15797
  }
15703
15798
  });
15704
15799
 
15705
- // src/commands/mws-load-wiki-folder.ts
15706
- var mws_load_wiki_folder_exports = {};
15707
- __export(mws_load_wiki_folder_exports, {
15708
- Command: () => Command3,
15709
- info: () => info3
15710
- });
15711
- import { resolve as resolve7 } from "path";
15712
- function makePluginBagName(type, publisher, name) {
15713
- return "$:/" + type + "/" + (publisher ? publisher + "/" : "") + name;
15714
- }
15715
- function loadWikiFolder({ $tw: $tw2, store, ...options }) {
15716
- const path5 = __require("path"), fs3 = __require("fs");
15717
- const wikiInfoPath = path5.resolve(options.wikiPath, $tw2.config.wikiInfo);
15718
- let wikiInfo;
15719
- if (fs3.existsSync(wikiInfoPath)) {
15720
- wikiInfo = $tw2.utils.parseJSONSafe(fs3.readFileSync(wikiInfoPath, "utf8"), function() {
15721
- return null;
15722
- });
15723
- }
15724
- if (!wikiInfo) return [];
15725
- const recipeList = [];
15726
- const processPlugins = /* @__PURE__ */ __name(function(type, plugins) {
15727
- $tw2.utils.each(plugins, function(pluginName) {
15728
- const parts = pluginName.split("/");
15729
- let publisher, name;
15730
- if (parts.length === 2) {
15731
- publisher = parts[0];
15732
- name = parts[1];
15733
- } else {
15734
- name = parts[0];
15735
- }
15736
- recipeList.push({ bag_name: makePluginBagName(type, publisher, name), with_acl: false });
15737
- });
15738
- }, "processPlugins");
15739
- processPlugins("plugins", wikiInfo.plugins);
15740
- processPlugins("themes", wikiInfo.themes);
15741
- processPlugins("languages", wikiInfo.languages);
15742
- recipeList.push({
15743
- bag_name: options.bagName,
15744
- with_acl: true
15745
- });
15746
- recipeList.reverse();
15747
- const tiddler_files_path = path5.resolve(options.wikiPath, $tw2.config.wikiTiddlersSubDir);
15748
- const tiddlersFromPath = $tw2.loadTiddlersFromPath(
15749
- resolve7($tw2.boot.corePath, $tw2.config.editionsPath, tiddler_files_path)
15750
- );
15751
- const is_plugin = false;
15752
- return [
15753
- // create the bag
15754
- store.upsertBag_PrismaPromise(options.bagName, options.bagDescription, is_plugin),
15755
- // create the recipe and recipe_bags entries
15756
- ...store.upsertRecipe_PrismaArray(
15757
- options.recipeName,
15758
- options.recipeDescription,
15759
- recipeList
15760
- ),
15761
- // save the tiddlers (this will skip attachments)
15762
- ...store.saveTiddlersFromPath_PrismaArray(tiddlersFromPath, options.bagName)
15763
- ];
15764
- }
15765
- var info3, _Command3, Command3;
15766
- var init_mws_load_wiki_folder = __esm({
15767
- "src/commands/mws-load-wiki-folder.ts"() {
15800
+ // node_modules/commander/lib/help.js
15801
+ var require_help = __commonJS({
15802
+ "node_modules/commander/lib/help.js"(exports) {
15768
15803
  "use strict";
15769
15804
  init_esm_shims();
15770
- init_TiddlerStore();
15771
- info3 = {
15772
- name: "mws-load-wiki-folder",
15773
- synchronous: true
15774
- };
15775
- _Command3 = class _Command3 {
15776
- constructor(params, commander, callback) {
15777
- this.params = params;
15778
- this.commander = commander;
15779
- this.callback = callback;
15805
+ var { humanReadableArgName } = require_argument();
15806
+ var _Help = class _Help {
15807
+ constructor() {
15808
+ this.helpWidth = void 0;
15809
+ this.minWidthToWrap = 40;
15810
+ this.sortSubcommands = false;
15811
+ this.sortOptions = false;
15812
+ this.showGlobalOptions = false;
15780
15813
  }
15781
- async execute() {
15814
+ /**
15815
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
15816
+ * and just before calling `formatHelp()`.
15817
+ *
15818
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
15819
+ *
15820
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
15821
+ */
15822
+ prepareContext(contextOptions) {
15823
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
15824
+ }
15825
+ /**
15826
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
15827
+ *
15828
+ * @param {Command} cmd
15829
+ * @returns {Command[]}
15830
+ */
15831
+ visibleCommands(cmd) {
15832
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
15833
+ const helpCommand = cmd._getHelpCommand();
15834
+ if (helpCommand && !helpCommand._hidden) {
15835
+ visibleCommands.push(helpCommand);
15836
+ }
15837
+ if (this.sortSubcommands) {
15838
+ visibleCommands.sort((a, b) => {
15839
+ return a.name().localeCompare(b.name());
15840
+ });
15841
+ }
15842
+ return visibleCommands;
15843
+ }
15844
+ /**
15845
+ * Compare options for sort.
15846
+ *
15847
+ * @param {Option} a
15848
+ * @param {Option} b
15849
+ * @returns {number}
15850
+ */
15851
+ compareOptions(a, b) {
15852
+ const getSortKey = /* @__PURE__ */ __name((option) => {
15853
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
15854
+ }, "getSortKey");
15855
+ return getSortKey(a).localeCompare(getSortKey(b));
15856
+ }
15857
+ /**
15858
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
15859
+ *
15860
+ * @param {Command} cmd
15861
+ * @returns {Option[]}
15862
+ */
15863
+ visibleOptions(cmd) {
15864
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
15865
+ const helpOption = cmd._getHelpOption();
15866
+ if (helpOption && !helpOption.hidden) {
15867
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
15868
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
15869
+ if (!removeShort && !removeLong) {
15870
+ visibleOptions.push(helpOption);
15871
+ } else if (helpOption.long && !removeLong) {
15872
+ visibleOptions.push(
15873
+ cmd.createOption(helpOption.long, helpOption.description)
15874
+ );
15875
+ } else if (helpOption.short && !removeShort) {
15876
+ visibleOptions.push(
15877
+ cmd.createOption(helpOption.short, helpOption.description)
15878
+ );
15879
+ }
15880
+ }
15881
+ if (this.sortOptions) {
15882
+ visibleOptions.sort(this.compareOptions);
15883
+ }
15884
+ return visibleOptions;
15885
+ }
15886
+ /**
15887
+ * Get an array of the visible global options. (Not including help.)
15888
+ *
15889
+ * @param {Command} cmd
15890
+ * @returns {Option[]}
15891
+ */
15892
+ visibleGlobalOptions(cmd) {
15893
+ if (!this.showGlobalOptions) return [];
15894
+ const globalOptions = [];
15895
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
15896
+ const visibleOptions = ancestorCmd.options.filter(
15897
+ (option) => !option.hidden
15898
+ );
15899
+ globalOptions.push(...visibleOptions);
15900
+ }
15901
+ if (this.sortOptions) {
15902
+ globalOptions.sort(this.compareOptions);
15903
+ }
15904
+ return globalOptions;
15905
+ }
15906
+ /**
15907
+ * Get an array of the arguments if any have a description.
15908
+ *
15909
+ * @param {Command} cmd
15910
+ * @returns {Argument[]}
15911
+ */
15912
+ visibleArguments(cmd) {
15913
+ if (cmd._argsDescription) {
15914
+ cmd.registeredArguments.forEach((argument) => {
15915
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
15916
+ });
15917
+ }
15918
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
15919
+ return cmd.registeredArguments;
15920
+ }
15921
+ return [];
15922
+ }
15923
+ /**
15924
+ * Get the command term to show in the list of subcommands.
15925
+ *
15926
+ * @param {Command} cmd
15927
+ * @returns {string}
15928
+ */
15929
+ subcommandTerm(cmd) {
15930
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
15931
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
15932
+ (args ? " " + args : "");
15933
+ }
15934
+ /**
15935
+ * Get the option term to show in the list of options.
15936
+ *
15937
+ * @param {Option} option
15938
+ * @returns {string}
15939
+ */
15940
+ optionTerm(option) {
15941
+ return option.flags;
15942
+ }
15943
+ /**
15944
+ * Get the argument term to show in the list of arguments.
15945
+ *
15946
+ * @param {Argument} argument
15947
+ * @returns {string}
15948
+ */
15949
+ argumentTerm(argument) {
15950
+ return argument.name();
15951
+ }
15952
+ /**
15953
+ * Get the longest command term length.
15954
+ *
15955
+ * @param {Command} cmd
15956
+ * @param {Help} helper
15957
+ * @returns {number}
15958
+ */
15959
+ longestSubcommandTermLength(cmd, helper) {
15960
+ return helper.visibleCommands(cmd).reduce((max, command) => {
15961
+ return Math.max(
15962
+ max,
15963
+ this.displayWidth(
15964
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
15965
+ )
15966
+ );
15967
+ }, 0);
15968
+ }
15969
+ /**
15970
+ * Get the longest option term length.
15971
+ *
15972
+ * @param {Command} cmd
15973
+ * @param {Help} helper
15974
+ * @returns {number}
15975
+ */
15976
+ longestOptionTermLength(cmd, helper) {
15977
+ return helper.visibleOptions(cmd).reduce((max, option) => {
15978
+ return Math.max(
15979
+ max,
15980
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
15981
+ );
15982
+ }, 0);
15983
+ }
15984
+ /**
15985
+ * Get the longest global option term length.
15986
+ *
15987
+ * @param {Command} cmd
15988
+ * @param {Help} helper
15989
+ * @returns {number}
15990
+ */
15991
+ longestGlobalOptionTermLength(cmd, helper) {
15992
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
15993
+ return Math.max(
15994
+ max,
15995
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
15996
+ );
15997
+ }, 0);
15998
+ }
15999
+ /**
16000
+ * Get the longest argument term length.
16001
+ *
16002
+ * @param {Command} cmd
16003
+ * @param {Help} helper
16004
+ * @returns {number}
16005
+ */
16006
+ longestArgumentTermLength(cmd, helper) {
16007
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
16008
+ return Math.max(
16009
+ max,
16010
+ this.displayWidth(
16011
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
16012
+ )
16013
+ );
16014
+ }, 0);
16015
+ }
16016
+ /**
16017
+ * Get the command usage to be displayed at the top of the built-in help.
16018
+ *
16019
+ * @param {Command} cmd
16020
+ * @returns {string}
16021
+ */
16022
+ commandUsage(cmd) {
16023
+ let cmdName = cmd._name;
16024
+ if (cmd._aliases[0]) {
16025
+ cmdName = cmdName + "|" + cmd._aliases[0];
16026
+ }
16027
+ let ancestorCmdNames = "";
16028
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
16029
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
16030
+ }
16031
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
16032
+ }
16033
+ /**
16034
+ * Get the description for the command.
16035
+ *
16036
+ * @param {Command} cmd
16037
+ * @returns {string}
16038
+ */
16039
+ commandDescription(cmd) {
16040
+ return cmd.description();
16041
+ }
16042
+ /**
16043
+ * Get the subcommand summary to show in the list of subcommands.
16044
+ * (Fallback to description for backwards compatibility.)
16045
+ *
16046
+ * @param {Command} cmd
16047
+ * @returns {string}
16048
+ */
16049
+ subcommandDescription(cmd) {
16050
+ return cmd.summary() || cmd.description();
16051
+ }
16052
+ /**
16053
+ * Get the option description to show in the list of options.
16054
+ *
16055
+ * @param {Option} option
16056
+ * @return {string}
16057
+ */
16058
+ optionDescription(option) {
16059
+ const extraInfo = [];
16060
+ if (option.argChoices) {
16061
+ extraInfo.push(
16062
+ // use stringify to match the display of the default value
16063
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
16064
+ );
16065
+ }
16066
+ if (option.defaultValue !== void 0) {
16067
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
16068
+ if (showDefault) {
16069
+ extraInfo.push(
16070
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
16071
+ );
16072
+ }
16073
+ }
16074
+ if (option.presetArg !== void 0 && option.optional) {
16075
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
16076
+ }
16077
+ if (option.envVar !== void 0) {
16078
+ extraInfo.push(`env: ${option.envVar}`);
16079
+ }
16080
+ if (extraInfo.length > 0) {
16081
+ return `${option.description} (${extraInfo.join(", ")})`;
16082
+ }
16083
+ return option.description;
16084
+ }
16085
+ /**
16086
+ * Get the argument description to show in the list of arguments.
16087
+ *
16088
+ * @param {Argument} argument
16089
+ * @return {string}
16090
+ */
16091
+ argumentDescription(argument) {
16092
+ const extraInfo = [];
16093
+ if (argument.argChoices) {
16094
+ extraInfo.push(
16095
+ // use stringify to match the display of the default value
16096
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
16097
+ );
16098
+ }
16099
+ if (argument.defaultValue !== void 0) {
16100
+ extraInfo.push(
16101
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
16102
+ );
16103
+ }
16104
+ if (extraInfo.length > 0) {
16105
+ const extraDescription = `(${extraInfo.join(", ")})`;
16106
+ if (argument.description) {
16107
+ return `${argument.description} ${extraDescription}`;
16108
+ }
16109
+ return extraDescription;
16110
+ }
16111
+ return argument.description;
16112
+ }
16113
+ /**
16114
+ * Generate the built-in help text.
16115
+ *
16116
+ * @param {Command} cmd
16117
+ * @param {Help} helper
16118
+ * @returns {string}
16119
+ */
16120
+ formatHelp(cmd, helper) {
16121
+ const termWidth = helper.padWidth(cmd, helper);
16122
+ const helpWidth = helper.helpWidth ?? 80;
16123
+ function callFormatItem(term, description) {
16124
+ return helper.formatItem(term, termWidth, description, helper);
16125
+ }
16126
+ __name(callFormatItem, "callFormatItem");
16127
+ let output = [
16128
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
16129
+ ""
16130
+ ];
16131
+ const commandDescription = helper.commandDescription(cmd);
16132
+ if (commandDescription.length > 0) {
16133
+ output = output.concat([
16134
+ helper.boxWrap(
16135
+ helper.styleCommandDescription(commandDescription),
16136
+ helpWidth
16137
+ ),
16138
+ ""
16139
+ ]);
16140
+ }
16141
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
16142
+ return callFormatItem(
16143
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
16144
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
16145
+ );
16146
+ });
16147
+ if (argumentList.length > 0) {
16148
+ output = output.concat([
16149
+ helper.styleTitle("Arguments:"),
16150
+ ...argumentList,
16151
+ ""
16152
+ ]);
16153
+ }
16154
+ const optionList = helper.visibleOptions(cmd).map((option) => {
16155
+ return callFormatItem(
16156
+ helper.styleOptionTerm(helper.optionTerm(option)),
16157
+ helper.styleOptionDescription(helper.optionDescription(option))
16158
+ );
16159
+ });
16160
+ if (optionList.length > 0) {
16161
+ output = output.concat([
16162
+ helper.styleTitle("Options:"),
16163
+ ...optionList,
16164
+ ""
16165
+ ]);
16166
+ }
16167
+ if (helper.showGlobalOptions) {
16168
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
16169
+ return callFormatItem(
16170
+ helper.styleOptionTerm(helper.optionTerm(option)),
16171
+ helper.styleOptionDescription(helper.optionDescription(option))
16172
+ );
16173
+ });
16174
+ if (globalOptionList.length > 0) {
16175
+ output = output.concat([
16176
+ helper.styleTitle("Global Options:"),
16177
+ ...globalOptionList,
16178
+ ""
16179
+ ]);
16180
+ }
16181
+ }
16182
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
16183
+ return callFormatItem(
16184
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
16185
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
16186
+ );
16187
+ });
16188
+ if (commandList.length > 0) {
16189
+ output = output.concat([
16190
+ helper.styleTitle("Commands:"),
16191
+ ...commandList,
16192
+ ""
16193
+ ]);
16194
+ }
16195
+ return output.join("\n");
16196
+ }
16197
+ /**
16198
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
16199
+ *
16200
+ * @param {string} str
16201
+ * @returns {number}
16202
+ */
16203
+ displayWidth(str) {
16204
+ return stripColor(str).length;
16205
+ }
16206
+ /**
16207
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
16208
+ *
16209
+ * @param {string} str
16210
+ * @returns {string}
16211
+ */
16212
+ styleTitle(str) {
16213
+ return str;
16214
+ }
16215
+ styleUsage(str) {
16216
+ return str.split(" ").map((word) => {
16217
+ if (word === "[options]") return this.styleOptionText(word);
16218
+ if (word === "[command]") return this.styleSubcommandText(word);
16219
+ if (word[0] === "[" || word[0] === "<")
16220
+ return this.styleArgumentText(word);
16221
+ return this.styleCommandText(word);
16222
+ }).join(" ");
16223
+ }
16224
+ styleCommandDescription(str) {
16225
+ return this.styleDescriptionText(str);
16226
+ }
16227
+ styleOptionDescription(str) {
16228
+ return this.styleDescriptionText(str);
16229
+ }
16230
+ styleSubcommandDescription(str) {
16231
+ return this.styleDescriptionText(str);
16232
+ }
16233
+ styleArgumentDescription(str) {
16234
+ return this.styleDescriptionText(str);
16235
+ }
16236
+ styleDescriptionText(str) {
16237
+ return str;
16238
+ }
16239
+ styleOptionTerm(str) {
16240
+ return this.styleOptionText(str);
16241
+ }
16242
+ styleSubcommandTerm(str) {
16243
+ return str.split(" ").map((word) => {
16244
+ if (word === "[options]") return this.styleOptionText(word);
16245
+ if (word[0] === "[" || word[0] === "<")
16246
+ return this.styleArgumentText(word);
16247
+ return this.styleSubcommandText(word);
16248
+ }).join(" ");
16249
+ }
16250
+ styleArgumentTerm(str) {
16251
+ return this.styleArgumentText(str);
16252
+ }
16253
+ styleOptionText(str) {
16254
+ return str;
16255
+ }
16256
+ styleArgumentText(str) {
16257
+ return str;
16258
+ }
16259
+ styleSubcommandText(str) {
16260
+ return str;
16261
+ }
16262
+ styleCommandText(str) {
16263
+ return str;
16264
+ }
16265
+ /**
16266
+ * Calculate the pad width from the maximum term length.
16267
+ *
16268
+ * @param {Command} cmd
16269
+ * @param {Help} helper
16270
+ * @returns {number}
16271
+ */
16272
+ padWidth(cmd, helper) {
16273
+ return Math.max(
16274
+ helper.longestOptionTermLength(cmd, helper),
16275
+ helper.longestGlobalOptionTermLength(cmd, helper),
16276
+ helper.longestSubcommandTermLength(cmd, helper),
16277
+ helper.longestArgumentTermLength(cmd, helper)
16278
+ );
16279
+ }
16280
+ /**
16281
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
16282
+ *
16283
+ * @param {string} str
16284
+ * @returns {boolean}
16285
+ */
16286
+ preformatted(str) {
16287
+ return /\n[^\S\r\n]/.test(str);
16288
+ }
16289
+ /**
16290
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
16291
+ *
16292
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
16293
+ * TTT DDD DDDD
16294
+ * DD DDD
16295
+ *
16296
+ * @param {string} term
16297
+ * @param {number} termWidth
16298
+ * @param {string} description
16299
+ * @param {Help} helper
16300
+ * @returns {string}
16301
+ */
16302
+ formatItem(term, termWidth, description, helper) {
16303
+ const itemIndent = 2;
16304
+ const itemIndentStr = " ".repeat(itemIndent);
16305
+ if (!description) return itemIndentStr + term;
16306
+ const paddedTerm = term.padEnd(
16307
+ termWidth + term.length - helper.displayWidth(term)
16308
+ );
16309
+ const spacerWidth = 2;
16310
+ const helpWidth = this.helpWidth ?? 80;
16311
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
16312
+ let formattedDescription;
16313
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
16314
+ formattedDescription = description;
16315
+ } else {
16316
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
16317
+ formattedDescription = wrappedDescription.replace(
16318
+ /\n/g,
16319
+ "\n" + " ".repeat(termWidth + spacerWidth)
16320
+ );
16321
+ }
16322
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
16323
+ ${itemIndentStr}`);
16324
+ }
16325
+ /**
16326
+ * Wrap a string at whitespace, preserving existing line breaks.
16327
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
16328
+ *
16329
+ * @param {string} str
16330
+ * @param {number} width
16331
+ * @returns {string}
16332
+ */
16333
+ boxWrap(str, width) {
16334
+ if (width < this.minWidthToWrap) return str;
16335
+ const rawLines = str.split(/\r\n|\n/);
16336
+ const chunkPattern = /[\s]*[^\s]+/g;
16337
+ const wrappedLines = [];
16338
+ rawLines.forEach((line) => {
16339
+ const chunks = line.match(chunkPattern);
16340
+ if (chunks === null) {
16341
+ wrappedLines.push("");
16342
+ return;
16343
+ }
16344
+ let sumChunks = [chunks.shift()];
16345
+ let sumWidth = this.displayWidth(sumChunks[0]);
16346
+ chunks.forEach((chunk) => {
16347
+ const visibleWidth = this.displayWidth(chunk);
16348
+ if (sumWidth + visibleWidth <= width) {
16349
+ sumChunks.push(chunk);
16350
+ sumWidth += visibleWidth;
16351
+ return;
16352
+ }
16353
+ wrappedLines.push(sumChunks.join(""));
16354
+ const nextChunk = chunk.trimStart();
16355
+ sumChunks = [nextChunk];
16356
+ sumWidth = this.displayWidth(nextChunk);
16357
+ });
16358
+ wrappedLines.push(sumChunks.join(""));
16359
+ });
16360
+ return wrappedLines.join("\n");
16361
+ }
16362
+ };
16363
+ __name(_Help, "Help");
16364
+ var Help2 = _Help;
16365
+ function stripColor(str) {
16366
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
16367
+ return str.replace(sgrPattern, "");
16368
+ }
16369
+ __name(stripColor, "stripColor");
16370
+ exports.Help = Help2;
16371
+ exports.stripColor = stripColor;
16372
+ }
16373
+ });
16374
+
16375
+ // node_modules/commander/lib/option.js
16376
+ var require_option = __commonJS({
16377
+ "node_modules/commander/lib/option.js"(exports) {
16378
+ "use strict";
16379
+ init_esm_shims();
16380
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
16381
+ var _Option = class _Option {
16382
+ /**
16383
+ * Initialize a new `Option` with the given `flags` and `description`.
16384
+ *
16385
+ * @param {string} flags
16386
+ * @param {string} [description]
16387
+ */
16388
+ constructor(flags, description) {
16389
+ this.flags = flags;
16390
+ this.description = description || "";
16391
+ this.required = flags.includes("<");
16392
+ this.optional = flags.includes("[");
16393
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
16394
+ this.mandatory = false;
16395
+ const optionFlags = splitOptionFlags(flags);
16396
+ this.short = optionFlags.shortFlag;
16397
+ this.long = optionFlags.longFlag;
16398
+ this.negate = false;
16399
+ if (this.long) {
16400
+ this.negate = this.long.startsWith("--no-");
16401
+ }
16402
+ this.defaultValue = void 0;
16403
+ this.defaultValueDescription = void 0;
16404
+ this.presetArg = void 0;
16405
+ this.envVar = void 0;
16406
+ this.parseArg = void 0;
16407
+ this.hidden = false;
16408
+ this.argChoices = void 0;
16409
+ this.conflictsWith = [];
16410
+ this.implied = void 0;
16411
+ }
16412
+ /**
16413
+ * Set the default value, and optionally supply the description to be displayed in the help.
16414
+ *
16415
+ * @param {*} value
16416
+ * @param {string} [description]
16417
+ * @return {Option}
16418
+ */
16419
+ default(value, description) {
16420
+ this.defaultValue = value;
16421
+ this.defaultValueDescription = description;
16422
+ return this;
16423
+ }
16424
+ /**
16425
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
16426
+ * The custom processing (parseArg) is called.
16427
+ *
16428
+ * @example
16429
+ * new Option('--color').default('GREYSCALE').preset('RGB');
16430
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
16431
+ *
16432
+ * @param {*} arg
16433
+ * @return {Option}
16434
+ */
16435
+ preset(arg) {
16436
+ this.presetArg = arg;
16437
+ return this;
16438
+ }
16439
+ /**
16440
+ * Add option name(s) that conflict with this option.
16441
+ * An error will be displayed if conflicting options are found during parsing.
16442
+ *
16443
+ * @example
16444
+ * new Option('--rgb').conflicts('cmyk');
16445
+ * new Option('--js').conflicts(['ts', 'jsx']);
16446
+ *
16447
+ * @param {(string | string[])} names
16448
+ * @return {Option}
16449
+ */
16450
+ conflicts(names) {
16451
+ this.conflictsWith = this.conflictsWith.concat(names);
16452
+ return this;
16453
+ }
16454
+ /**
16455
+ * Specify implied option values for when this option is set and the implied options are not.
16456
+ *
16457
+ * The custom processing (parseArg) is not called on the implied values.
16458
+ *
16459
+ * @example
16460
+ * program
16461
+ * .addOption(new Option('--log', 'write logging information to file'))
16462
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
16463
+ *
16464
+ * @param {object} impliedOptionValues
16465
+ * @return {Option}
16466
+ */
16467
+ implies(impliedOptionValues) {
16468
+ let newImplied = impliedOptionValues;
16469
+ if (typeof impliedOptionValues === "string") {
16470
+ newImplied = { [impliedOptionValues]: true };
16471
+ }
16472
+ this.implied = Object.assign(this.implied || {}, newImplied);
16473
+ return this;
16474
+ }
16475
+ /**
16476
+ * Set environment variable to check for option value.
16477
+ *
16478
+ * An environment variable is only used if when processed the current option value is
16479
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
16480
+ *
16481
+ * @param {string} name
16482
+ * @return {Option}
16483
+ */
16484
+ env(name) {
16485
+ this.envVar = name;
16486
+ return this;
16487
+ }
16488
+ /**
16489
+ * Set the custom handler for processing CLI option arguments into option values.
16490
+ *
16491
+ * @param {Function} [fn]
16492
+ * @return {Option}
16493
+ */
16494
+ argParser(fn) {
16495
+ this.parseArg = fn;
16496
+ return this;
16497
+ }
16498
+ /**
16499
+ * Whether the option is mandatory and must have a value after parsing.
16500
+ *
16501
+ * @param {boolean} [mandatory=true]
16502
+ * @return {Option}
16503
+ */
16504
+ makeOptionMandatory(mandatory = true) {
16505
+ this.mandatory = !!mandatory;
16506
+ return this;
16507
+ }
16508
+ /**
16509
+ * Hide option in help.
16510
+ *
16511
+ * @param {boolean} [hide=true]
16512
+ * @return {Option}
16513
+ */
16514
+ hideHelp(hide = true) {
16515
+ this.hidden = !!hide;
16516
+ return this;
16517
+ }
16518
+ /**
16519
+ * @package
16520
+ */
16521
+ _concatValue(value, previous) {
16522
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
16523
+ return [value];
16524
+ }
16525
+ return previous.concat(value);
16526
+ }
16527
+ /**
16528
+ * Only allow option value to be one of choices.
16529
+ *
16530
+ * @param {string[]} values
16531
+ * @return {Option}
16532
+ */
16533
+ choices(values) {
16534
+ this.argChoices = values.slice();
16535
+ this.parseArg = (arg, previous) => {
16536
+ if (!this.argChoices.includes(arg)) {
16537
+ throw new InvalidArgumentError2(
16538
+ `Allowed choices are ${this.argChoices.join(", ")}.`
16539
+ );
16540
+ }
16541
+ if (this.variadic) {
16542
+ return this._concatValue(arg, previous);
16543
+ }
16544
+ return arg;
16545
+ };
16546
+ return this;
16547
+ }
16548
+ /**
16549
+ * Return option name.
16550
+ *
16551
+ * @return {string}
16552
+ */
16553
+ name() {
16554
+ if (this.long) {
16555
+ return this.long.replace(/^--/, "");
16556
+ }
16557
+ return this.short.replace(/^-/, "");
16558
+ }
16559
+ /**
16560
+ * Return option name, in a camelcase format that can be used
16561
+ * as an object attribute key.
16562
+ *
16563
+ * @return {string}
16564
+ */
16565
+ attributeName() {
16566
+ if (this.negate) {
16567
+ return camelcase(this.name().replace(/^no-/, ""));
16568
+ }
16569
+ return camelcase(this.name());
16570
+ }
16571
+ /**
16572
+ * Check if `arg` matches the short or long flag.
16573
+ *
16574
+ * @param {string} arg
16575
+ * @return {boolean}
16576
+ * @package
16577
+ */
16578
+ is(arg) {
16579
+ return this.short === arg || this.long === arg;
16580
+ }
16581
+ /**
16582
+ * Return whether a boolean option.
16583
+ *
16584
+ * Options are one of boolean, negated, required argument, or optional argument.
16585
+ *
16586
+ * @return {boolean}
16587
+ * @package
16588
+ */
16589
+ isBoolean() {
16590
+ return !this.required && !this.optional && !this.negate;
16591
+ }
16592
+ };
16593
+ __name(_Option, "Option");
16594
+ var Option2 = _Option;
16595
+ var _DualOptions = class _DualOptions {
16596
+ /**
16597
+ * @param {Option[]} options
16598
+ */
16599
+ constructor(options) {
16600
+ this.positiveOptions = /* @__PURE__ */ new Map();
16601
+ this.negativeOptions = /* @__PURE__ */ new Map();
16602
+ this.dualOptions = /* @__PURE__ */ new Set();
16603
+ options.forEach((option) => {
16604
+ if (option.negate) {
16605
+ this.negativeOptions.set(option.attributeName(), option);
16606
+ } else {
16607
+ this.positiveOptions.set(option.attributeName(), option);
16608
+ }
16609
+ });
16610
+ this.negativeOptions.forEach((value, key) => {
16611
+ if (this.positiveOptions.has(key)) {
16612
+ this.dualOptions.add(key);
16613
+ }
16614
+ });
16615
+ }
16616
+ /**
16617
+ * Did the value come from the option, and not from possible matching dual option?
16618
+ *
16619
+ * @param {*} value
16620
+ * @param {Option} option
16621
+ * @returns {boolean}
16622
+ */
16623
+ valueFromOption(value, option) {
16624
+ const optionKey = option.attributeName();
16625
+ if (!this.dualOptions.has(optionKey)) return true;
16626
+ const preset = this.negativeOptions.get(optionKey).presetArg;
16627
+ const negativeValue = preset !== void 0 ? preset : false;
16628
+ return option.negate === (negativeValue === value);
16629
+ }
16630
+ };
16631
+ __name(_DualOptions, "DualOptions");
16632
+ var DualOptions = _DualOptions;
16633
+ function camelcase(str) {
16634
+ return str.split("-").reduce((str2, word) => {
16635
+ return str2 + word[0].toUpperCase() + word.slice(1);
16636
+ });
16637
+ }
16638
+ __name(camelcase, "camelcase");
16639
+ function splitOptionFlags(flags) {
16640
+ let shortFlag;
16641
+ let longFlag;
16642
+ const shortFlagExp = /^-[^-]$/;
16643
+ const longFlagExp = /^--[^-]/;
16644
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
16645
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
16646
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
16647
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
16648
+ shortFlag = flagParts.shift();
16649
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
16650
+ shortFlag = longFlag;
16651
+ longFlag = flagParts.shift();
16652
+ }
16653
+ if (flagParts[0].startsWith("-")) {
16654
+ const unsupportedFlag = flagParts[0];
16655
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
16656
+ if (/^-[^-][^-]/.test(unsupportedFlag))
16657
+ throw new Error(
16658
+ `${baseError}
16659
+ - a short flag is a single dash and a single character
16660
+ - either use a single dash and a single character (for a short flag)
16661
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
16662
+ );
16663
+ if (shortFlagExp.test(unsupportedFlag))
16664
+ throw new Error(`${baseError}
16665
+ - too many short flags`);
16666
+ if (longFlagExp.test(unsupportedFlag))
16667
+ throw new Error(`${baseError}
16668
+ - too many long flags`);
16669
+ throw new Error(`${baseError}
16670
+ - unrecognised flag format`);
16671
+ }
16672
+ if (shortFlag === void 0 && longFlag === void 0)
16673
+ throw new Error(
16674
+ `option creation failed due to no flags found in '${flags}'.`
16675
+ );
16676
+ return { shortFlag, longFlag };
16677
+ }
16678
+ __name(splitOptionFlags, "splitOptionFlags");
16679
+ exports.Option = Option2;
16680
+ exports.DualOptions = DualOptions;
16681
+ }
16682
+ });
16683
+
16684
+ // node_modules/commander/lib/suggestSimilar.js
16685
+ var require_suggestSimilar = __commonJS({
16686
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
16687
+ "use strict";
16688
+ init_esm_shims();
16689
+ var maxDistance = 3;
16690
+ function editDistance(a, b) {
16691
+ if (Math.abs(a.length - b.length) > maxDistance)
16692
+ return Math.max(a.length, b.length);
16693
+ const d = [];
16694
+ for (let i = 0; i <= a.length; i++) {
16695
+ d[i] = [i];
16696
+ }
16697
+ for (let j = 0; j <= b.length; j++) {
16698
+ d[0][j] = j;
16699
+ }
16700
+ for (let j = 1; j <= b.length; j++) {
16701
+ for (let i = 1; i <= a.length; i++) {
16702
+ let cost = 1;
16703
+ if (a[i - 1] === b[j - 1]) {
16704
+ cost = 0;
16705
+ } else {
16706
+ cost = 1;
16707
+ }
16708
+ d[i][j] = Math.min(
16709
+ d[i - 1][j] + 1,
16710
+ // deletion
16711
+ d[i][j - 1] + 1,
16712
+ // insertion
16713
+ d[i - 1][j - 1] + cost
16714
+ // substitution
16715
+ );
16716
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
16717
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
16718
+ }
16719
+ }
16720
+ }
16721
+ return d[a.length][b.length];
16722
+ }
16723
+ __name(editDistance, "editDistance");
16724
+ function suggestSimilar(word, candidates) {
16725
+ if (!candidates || candidates.length === 0) return "";
16726
+ candidates = Array.from(new Set(candidates));
16727
+ const searchingOptions = word.startsWith("--");
16728
+ if (searchingOptions) {
16729
+ word = word.slice(2);
16730
+ candidates = candidates.map((candidate) => candidate.slice(2));
16731
+ }
16732
+ let similar = [];
16733
+ let bestDistance = maxDistance;
16734
+ const minSimilarity = 0.4;
16735
+ candidates.forEach((candidate) => {
16736
+ if (candidate.length <= 1) return;
16737
+ const distance = editDistance(word, candidate);
16738
+ const length = Math.max(word.length, candidate.length);
16739
+ const similarity = (length - distance) / length;
16740
+ if (similarity > minSimilarity) {
16741
+ if (distance < bestDistance) {
16742
+ bestDistance = distance;
16743
+ similar = [candidate];
16744
+ } else if (distance === bestDistance) {
16745
+ similar.push(candidate);
16746
+ }
16747
+ }
16748
+ });
16749
+ similar.sort((a, b) => a.localeCompare(b));
16750
+ if (searchingOptions) {
16751
+ similar = similar.map((candidate) => `--${candidate}`);
16752
+ }
16753
+ if (similar.length > 1) {
16754
+ return `
16755
+ (Did you mean one of ${similar.join(", ")}?)`;
16756
+ }
16757
+ if (similar.length === 1) {
16758
+ return `
16759
+ (Did you mean ${similar[0]}?)`;
16760
+ }
16761
+ return "";
16762
+ }
16763
+ __name(suggestSimilar, "suggestSimilar");
16764
+ exports.suggestSimilar = suggestSimilar;
16765
+ }
16766
+ });
16767
+
16768
+ // node_modules/commander/lib/command.js
16769
+ var require_command = __commonJS({
16770
+ "node_modules/commander/lib/command.js"(exports) {
16771
+ "use strict";
16772
+ init_esm_shims();
16773
+ var EventEmitter = __require("node:events").EventEmitter;
16774
+ var childProcess = __require("node:child_process");
16775
+ var path5 = __require("node:path");
16776
+ var fs3 = __require("node:fs");
16777
+ var process2 = __require("node:process");
16778
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
16779
+ var { CommanderError: CommanderError2 } = require_error();
16780
+ var { Help: Help2, stripColor } = require_help();
16781
+ var { Option: Option2, DualOptions } = require_option();
16782
+ var { suggestSimilar } = require_suggestSimilar();
16783
+ var _Command12 = class _Command12 extends EventEmitter {
16784
+ /**
16785
+ * Initialize a new `Command`.
16786
+ *
16787
+ * @param {string} [name]
16788
+ */
16789
+ constructor(name) {
16790
+ super();
16791
+ this.commands = [];
16792
+ this.options = [];
16793
+ this.parent = null;
16794
+ this._allowUnknownOption = false;
16795
+ this._allowExcessArguments = false;
16796
+ this.registeredArguments = [];
16797
+ this._args = this.registeredArguments;
16798
+ this.args = [];
16799
+ this.rawArgs = [];
16800
+ this.processedArgs = [];
16801
+ this._scriptPath = null;
16802
+ this._name = name || "";
16803
+ this._optionValues = {};
16804
+ this._optionValueSources = {};
16805
+ this._storeOptionsAsProperties = false;
16806
+ this._actionHandler = null;
16807
+ this._executableHandler = false;
16808
+ this._executableFile = null;
16809
+ this._executableDir = null;
16810
+ this._defaultCommandName = null;
16811
+ this._exitCallback = null;
16812
+ this._aliases = [];
16813
+ this._combineFlagAndOptionalValue = true;
16814
+ this._description = "";
16815
+ this._summary = "";
16816
+ this._argsDescription = void 0;
16817
+ this._enablePositionalOptions = false;
16818
+ this._passThroughOptions = false;
16819
+ this._lifeCycleHooks = {};
16820
+ this._showHelpAfterError = false;
16821
+ this._showSuggestionAfterError = true;
16822
+ this._savedState = null;
16823
+ this._outputConfiguration = {
16824
+ writeOut: /* @__PURE__ */ __name((str) => process2.stdout.write(str), "writeOut"),
16825
+ writeErr: /* @__PURE__ */ __name((str) => process2.stderr.write(str), "writeErr"),
16826
+ outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError"),
16827
+ getOutHelpWidth: /* @__PURE__ */ __name(() => process2.stdout.isTTY ? process2.stdout.columns : void 0, "getOutHelpWidth"),
16828
+ getErrHelpWidth: /* @__PURE__ */ __name(() => process2.stderr.isTTY ? process2.stderr.columns : void 0, "getErrHelpWidth"),
16829
+ getOutHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()), "getOutHasColors"),
16830
+ getErrHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()), "getErrHasColors"),
16831
+ stripColor: /* @__PURE__ */ __name((str) => stripColor(str), "stripColor")
16832
+ };
16833
+ this._hidden = false;
16834
+ this._helpOption = void 0;
16835
+ this._addImplicitHelpCommand = void 0;
16836
+ this._helpCommand = void 0;
16837
+ this._helpConfiguration = {};
16838
+ }
16839
+ /**
16840
+ * Copy settings that are useful to have in common across root command and subcommands.
16841
+ *
16842
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
16843
+ *
16844
+ * @param {Command} sourceCommand
16845
+ * @return {Command} `this` command for chaining
16846
+ */
16847
+ copyInheritedSettings(sourceCommand) {
16848
+ this._outputConfiguration = sourceCommand._outputConfiguration;
16849
+ this._helpOption = sourceCommand._helpOption;
16850
+ this._helpCommand = sourceCommand._helpCommand;
16851
+ this._helpConfiguration = sourceCommand._helpConfiguration;
16852
+ this._exitCallback = sourceCommand._exitCallback;
16853
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
16854
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
16855
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
16856
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
16857
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
16858
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
16859
+ return this;
16860
+ }
16861
+ /**
16862
+ * @returns {Command[]}
16863
+ * @private
16864
+ */
16865
+ _getCommandAndAncestors() {
16866
+ const result = [];
16867
+ for (let command = this; command; command = command.parent) {
16868
+ result.push(command);
16869
+ }
16870
+ return result;
16871
+ }
16872
+ /**
16873
+ * Define a command.
16874
+ *
16875
+ * There are two styles of command: pay attention to where to put the description.
16876
+ *
16877
+ * @example
16878
+ * // Command implemented using action handler (description is supplied separately to `.command`)
16879
+ * program
16880
+ * .command('clone <source> [destination]')
16881
+ * .description('clone a repository into a newly created directory')
16882
+ * .action((source, destination) => {
16883
+ * console.log('clone command called');
16884
+ * });
16885
+ *
16886
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
16887
+ * program
16888
+ * .command('start <service>', 'start named service')
16889
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
16890
+ *
16891
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
16892
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
16893
+ * @param {object} [execOpts] - configuration options (for executable)
16894
+ * @return {Command} returns new command for action handler, or `this` for executable command
16895
+ */
16896
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
16897
+ let desc = actionOptsOrExecDesc;
16898
+ let opts = execOpts;
16899
+ if (typeof desc === "object" && desc !== null) {
16900
+ opts = desc;
16901
+ desc = null;
16902
+ }
16903
+ opts = opts || {};
16904
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
16905
+ const cmd = this.createCommand(name);
16906
+ if (desc) {
16907
+ cmd.description(desc);
16908
+ cmd._executableHandler = true;
16909
+ }
16910
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
16911
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
16912
+ cmd._executableFile = opts.executableFile || null;
16913
+ if (args) cmd.arguments(args);
16914
+ this._registerCommand(cmd);
16915
+ cmd.parent = this;
16916
+ cmd.copyInheritedSettings(this);
16917
+ if (desc) return this;
16918
+ return cmd;
16919
+ }
16920
+ /**
16921
+ * Factory routine to create a new unattached command.
16922
+ *
16923
+ * See .command() for creating an attached subcommand, which uses this routine to
16924
+ * create the command. You can override createCommand to customise subcommands.
16925
+ *
16926
+ * @param {string} [name]
16927
+ * @return {Command} new command
16928
+ */
16929
+ createCommand(name) {
16930
+ return new _Command12(name);
16931
+ }
16932
+ /**
16933
+ * You can customise the help with a subclass of Help by overriding createHelp,
16934
+ * or by overriding Help properties using configureHelp().
16935
+ *
16936
+ * @return {Help}
16937
+ */
16938
+ createHelp() {
16939
+ return Object.assign(new Help2(), this.configureHelp());
16940
+ }
16941
+ /**
16942
+ * You can customise the help by overriding Help properties using configureHelp(),
16943
+ * or with a subclass of Help by overriding createHelp().
16944
+ *
16945
+ * @param {object} [configuration] - configuration options
16946
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
16947
+ */
16948
+ configureHelp(configuration) {
16949
+ if (configuration === void 0) return this._helpConfiguration;
16950
+ this._helpConfiguration = configuration;
16951
+ return this;
16952
+ }
16953
+ /**
16954
+ * The default output goes to stdout and stderr. You can customise this for special
16955
+ * applications. You can also customise the display of errors by overriding outputError.
16956
+ *
16957
+ * The configuration properties are all functions:
16958
+ *
16959
+ * // change how output being written, defaults to stdout and stderr
16960
+ * writeOut(str)
16961
+ * writeErr(str)
16962
+ * // change how output being written for errors, defaults to writeErr
16963
+ * outputError(str, write) // used for displaying errors and not used for displaying help
16964
+ * // specify width for wrapping help
16965
+ * getOutHelpWidth()
16966
+ * getErrHelpWidth()
16967
+ * // color support, currently only used with Help
16968
+ * getOutHasColors()
16969
+ * getErrHasColors()
16970
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
16971
+ *
16972
+ * @param {object} [configuration] - configuration options
16973
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
16974
+ */
16975
+ configureOutput(configuration) {
16976
+ if (configuration === void 0) return this._outputConfiguration;
16977
+ Object.assign(this._outputConfiguration, configuration);
16978
+ return this;
16979
+ }
16980
+ /**
16981
+ * Display the help or a custom message after an error occurs.
16982
+ *
16983
+ * @param {(boolean|string)} [displayHelp]
16984
+ * @return {Command} `this` command for chaining
16985
+ */
16986
+ showHelpAfterError(displayHelp = true) {
16987
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
16988
+ this._showHelpAfterError = displayHelp;
16989
+ return this;
16990
+ }
16991
+ /**
16992
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
16993
+ *
16994
+ * @param {boolean} [displaySuggestion]
16995
+ * @return {Command} `this` command for chaining
16996
+ */
16997
+ showSuggestionAfterError(displaySuggestion = true) {
16998
+ this._showSuggestionAfterError = !!displaySuggestion;
16999
+ return this;
17000
+ }
17001
+ /**
17002
+ * Add a prepared subcommand.
17003
+ *
17004
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
17005
+ *
17006
+ * @param {Command} cmd - new subcommand
17007
+ * @param {object} [opts] - configuration options
17008
+ * @return {Command} `this` command for chaining
17009
+ */
17010
+ addCommand(cmd, opts) {
17011
+ if (!cmd._name) {
17012
+ throw new Error(`Command passed to .addCommand() must have a name
17013
+ - specify the name in Command constructor or using .name()`);
17014
+ }
17015
+ opts = opts || {};
17016
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
17017
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
17018
+ this._registerCommand(cmd);
17019
+ cmd.parent = this;
17020
+ cmd._checkForBrokenPassThrough();
17021
+ return this;
17022
+ }
17023
+ /**
17024
+ * Factory routine to create a new unattached argument.
17025
+ *
17026
+ * See .argument() for creating an attached argument, which uses this routine to
17027
+ * create the argument. You can override createArgument to return a custom argument.
17028
+ *
17029
+ * @param {string} name
17030
+ * @param {string} [description]
17031
+ * @return {Argument} new argument
17032
+ */
17033
+ createArgument(name, description) {
17034
+ return new Argument2(name, description);
17035
+ }
17036
+ /**
17037
+ * Define argument syntax for command.
17038
+ *
17039
+ * The default is that the argument is required, and you can explicitly
17040
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
17041
+ *
17042
+ * @example
17043
+ * program.argument('<input-file>');
17044
+ * program.argument('[output-file]');
17045
+ *
17046
+ * @param {string} name
17047
+ * @param {string} [description]
17048
+ * @param {(Function|*)} [fn] - custom argument processing function
17049
+ * @param {*} [defaultValue]
17050
+ * @return {Command} `this` command for chaining
17051
+ */
17052
+ argument(name, description, fn, defaultValue) {
17053
+ const argument = this.createArgument(name, description);
17054
+ if (typeof fn === "function") {
17055
+ argument.default(defaultValue).argParser(fn);
17056
+ } else {
17057
+ argument.default(fn);
17058
+ }
17059
+ this.addArgument(argument);
17060
+ return this;
17061
+ }
17062
+ /**
17063
+ * Define argument syntax for command, adding multiple at once (without descriptions).
17064
+ *
17065
+ * See also .argument().
17066
+ *
17067
+ * @example
17068
+ * program.arguments('<cmd> [env]');
17069
+ *
17070
+ * @param {string} names
17071
+ * @return {Command} `this` command for chaining
17072
+ */
17073
+ arguments(names) {
17074
+ names.trim().split(/ +/).forEach((detail) => {
17075
+ this.argument(detail);
17076
+ });
17077
+ return this;
17078
+ }
17079
+ /**
17080
+ * Define argument syntax for command, adding a prepared argument.
17081
+ *
17082
+ * @param {Argument} argument
17083
+ * @return {Command} `this` command for chaining
17084
+ */
17085
+ addArgument(argument) {
17086
+ const previousArgument = this.registeredArguments.slice(-1)[0];
17087
+ if (previousArgument && previousArgument.variadic) {
17088
+ throw new Error(
17089
+ `only the last argument can be variadic '${previousArgument.name()}'`
17090
+ );
17091
+ }
17092
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
17093
+ throw new Error(
17094
+ `a default value for a required argument is never used: '${argument.name()}'`
17095
+ );
17096
+ }
17097
+ this.registeredArguments.push(argument);
17098
+ return this;
17099
+ }
17100
+ /**
17101
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
17102
+ *
17103
+ * @example
17104
+ * program.helpCommand('help [cmd]');
17105
+ * program.helpCommand('help [cmd]', 'show help');
17106
+ * program.helpCommand(false); // suppress default help command
17107
+ * program.helpCommand(true); // add help command even if no subcommands
17108
+ *
17109
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
17110
+ * @param {string} [description] - custom description
17111
+ * @return {Command} `this` command for chaining
17112
+ */
17113
+ helpCommand(enableOrNameAndArgs, description) {
17114
+ if (typeof enableOrNameAndArgs === "boolean") {
17115
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
17116
+ return this;
17117
+ }
17118
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
17119
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
17120
+ const helpDescription = description ?? "display help for command";
17121
+ const helpCommand = this.createCommand(helpName);
17122
+ helpCommand.helpOption(false);
17123
+ if (helpArgs) helpCommand.arguments(helpArgs);
17124
+ if (helpDescription) helpCommand.description(helpDescription);
17125
+ this._addImplicitHelpCommand = true;
17126
+ this._helpCommand = helpCommand;
17127
+ return this;
17128
+ }
17129
+ /**
17130
+ * Add prepared custom help command.
17131
+ *
17132
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
17133
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
17134
+ * @return {Command} `this` command for chaining
17135
+ */
17136
+ addHelpCommand(helpCommand, deprecatedDescription) {
17137
+ if (typeof helpCommand !== "object") {
17138
+ this.helpCommand(helpCommand, deprecatedDescription);
17139
+ return this;
17140
+ }
17141
+ this._addImplicitHelpCommand = true;
17142
+ this._helpCommand = helpCommand;
17143
+ return this;
17144
+ }
17145
+ /**
17146
+ * Lazy create help command.
17147
+ *
17148
+ * @return {(Command|null)}
17149
+ * @package
17150
+ */
17151
+ _getHelpCommand() {
17152
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
17153
+ if (hasImplicitHelpCommand) {
17154
+ if (this._helpCommand === void 0) {
17155
+ this.helpCommand(void 0, void 0);
17156
+ }
17157
+ return this._helpCommand;
17158
+ }
17159
+ return null;
17160
+ }
17161
+ /**
17162
+ * Add hook for life cycle event.
17163
+ *
17164
+ * @param {string} event
17165
+ * @param {Function} listener
17166
+ * @return {Command} `this` command for chaining
17167
+ */
17168
+ hook(event, listener) {
17169
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
17170
+ if (!allowedValues.includes(event)) {
17171
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
17172
+ Expecting one of '${allowedValues.join("', '")}'`);
17173
+ }
17174
+ if (this._lifeCycleHooks[event]) {
17175
+ this._lifeCycleHooks[event].push(listener);
17176
+ } else {
17177
+ this._lifeCycleHooks[event] = [listener];
17178
+ }
17179
+ return this;
17180
+ }
17181
+ /**
17182
+ * Register callback to use as replacement for calling process.exit.
17183
+ *
17184
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
17185
+ * @return {Command} `this` command for chaining
17186
+ */
17187
+ exitOverride(fn) {
17188
+ if (fn) {
17189
+ this._exitCallback = fn;
17190
+ } else {
17191
+ this._exitCallback = (err) => {
17192
+ if (err.code !== "commander.executeSubCommandAsync") {
17193
+ throw err;
17194
+ } else {
17195
+ }
17196
+ };
17197
+ }
17198
+ return this;
17199
+ }
17200
+ /**
17201
+ * Call process.exit, and _exitCallback if defined.
17202
+ *
17203
+ * @param {number} exitCode exit code for using with process.exit
17204
+ * @param {string} code an id string representing the error
17205
+ * @param {string} message human-readable description of the error
17206
+ * @return never
17207
+ * @private
17208
+ */
17209
+ _exit(exitCode, code, message) {
17210
+ if (this._exitCallback) {
17211
+ this._exitCallback(new CommanderError2(exitCode, code, message));
17212
+ }
17213
+ process2.exit(exitCode);
17214
+ }
17215
+ /**
17216
+ * Register callback `fn` for the command.
17217
+ *
17218
+ * @example
17219
+ * program
17220
+ * .command('serve')
17221
+ * .description('start service')
17222
+ * .action(function() {
17223
+ * // do work here
17224
+ * });
17225
+ *
17226
+ * @param {Function} fn
17227
+ * @return {Command} `this` command for chaining
17228
+ */
17229
+ action(fn) {
17230
+ const listener = /* @__PURE__ */ __name((args) => {
17231
+ const expectedArgsCount = this.registeredArguments.length;
17232
+ const actionArgs = args.slice(0, expectedArgsCount);
17233
+ if (this._storeOptionsAsProperties) {
17234
+ actionArgs[expectedArgsCount] = this;
17235
+ } else {
17236
+ actionArgs[expectedArgsCount] = this.opts();
17237
+ }
17238
+ actionArgs.push(this);
17239
+ return fn.apply(this, actionArgs);
17240
+ }, "listener");
17241
+ this._actionHandler = listener;
17242
+ return this;
17243
+ }
17244
+ /**
17245
+ * Factory routine to create a new unattached option.
17246
+ *
17247
+ * See .option() for creating an attached option, which uses this routine to
17248
+ * create the option. You can override createOption to return a custom option.
17249
+ *
17250
+ * @param {string} flags
17251
+ * @param {string} [description]
17252
+ * @return {Option} new option
17253
+ */
17254
+ createOption(flags, description) {
17255
+ return new Option2(flags, description);
17256
+ }
17257
+ /**
17258
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
17259
+ *
17260
+ * @param {(Option | Argument)} target
17261
+ * @param {string} value
17262
+ * @param {*} previous
17263
+ * @param {string} invalidArgumentMessage
17264
+ * @private
17265
+ */
17266
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
17267
+ try {
17268
+ return target.parseArg(value, previous);
17269
+ } catch (err) {
17270
+ if (err.code === "commander.invalidArgument") {
17271
+ const message = `${invalidArgumentMessage} ${err.message}`;
17272
+ this.error(message, { exitCode: err.exitCode, code: err.code });
17273
+ }
17274
+ throw err;
17275
+ }
17276
+ }
17277
+ /**
17278
+ * Check for option flag conflicts.
17279
+ * Register option if no conflicts found, or throw on conflict.
17280
+ *
17281
+ * @param {Option} option
17282
+ * @private
17283
+ */
17284
+ _registerOption(option) {
17285
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
17286
+ if (matchingOption) {
17287
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
17288
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
17289
+ - already used by option '${matchingOption.flags}'`);
17290
+ }
17291
+ this.options.push(option);
17292
+ }
17293
+ /**
17294
+ * Check for command name and alias conflicts with existing commands.
17295
+ * Register command if no conflicts found, or throw on conflict.
17296
+ *
17297
+ * @param {Command} command
17298
+ * @private
17299
+ */
17300
+ _registerCommand(command) {
17301
+ const knownBy = /* @__PURE__ */ __name((cmd) => {
17302
+ return [cmd.name()].concat(cmd.aliases());
17303
+ }, "knownBy");
17304
+ const alreadyUsed = knownBy(command).find(
17305
+ (name) => this._findCommand(name)
17306
+ );
17307
+ if (alreadyUsed) {
17308
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
17309
+ const newCmd = knownBy(command).join("|");
17310
+ throw new Error(
17311
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
17312
+ );
17313
+ }
17314
+ this.commands.push(command);
17315
+ }
17316
+ /**
17317
+ * Add an option.
17318
+ *
17319
+ * @param {Option} option
17320
+ * @return {Command} `this` command for chaining
17321
+ */
17322
+ addOption(option) {
17323
+ this._registerOption(option);
17324
+ const oname = option.name();
17325
+ const name = option.attributeName();
17326
+ if (option.negate) {
17327
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
17328
+ if (!this._findOption(positiveLongFlag)) {
17329
+ this.setOptionValueWithSource(
17330
+ name,
17331
+ option.defaultValue === void 0 ? true : option.defaultValue,
17332
+ "default"
17333
+ );
17334
+ }
17335
+ } else if (option.defaultValue !== void 0) {
17336
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
17337
+ }
17338
+ const handleOptionValue = /* @__PURE__ */ __name((val, invalidValueMessage, valueSource) => {
17339
+ if (val == null && option.presetArg !== void 0) {
17340
+ val = option.presetArg;
17341
+ }
17342
+ const oldValue = this.getOptionValue(name);
17343
+ if (val !== null && option.parseArg) {
17344
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
17345
+ } else if (val !== null && option.variadic) {
17346
+ val = option._concatValue(val, oldValue);
17347
+ }
17348
+ if (val == null) {
17349
+ if (option.negate) {
17350
+ val = false;
17351
+ } else if (option.isBoolean() || option.optional) {
17352
+ val = true;
17353
+ } else {
17354
+ val = "";
17355
+ }
17356
+ }
17357
+ this.setOptionValueWithSource(name, val, valueSource);
17358
+ }, "handleOptionValue");
17359
+ this.on("option:" + oname, (val) => {
17360
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
17361
+ handleOptionValue(val, invalidValueMessage, "cli");
17362
+ });
17363
+ if (option.envVar) {
17364
+ this.on("optionEnv:" + oname, (val) => {
17365
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
17366
+ handleOptionValue(val, invalidValueMessage, "env");
17367
+ });
17368
+ }
17369
+ return this;
17370
+ }
17371
+ /**
17372
+ * Internal implementation shared by .option() and .requiredOption()
17373
+ *
17374
+ * @return {Command} `this` command for chaining
17375
+ * @private
17376
+ */
17377
+ _optionEx(config, flags, description, fn, defaultValue) {
17378
+ if (typeof flags === "object" && flags instanceof Option2) {
17379
+ throw new Error(
17380
+ "To add an Option object use addOption() instead of option() or requiredOption()"
17381
+ );
17382
+ }
17383
+ const option = this.createOption(flags, description);
17384
+ option.makeOptionMandatory(!!config.mandatory);
17385
+ if (typeof fn === "function") {
17386
+ option.default(defaultValue).argParser(fn);
17387
+ } else if (fn instanceof RegExp) {
17388
+ const regex = fn;
17389
+ fn = /* @__PURE__ */ __name((val, def) => {
17390
+ const m = regex.exec(val);
17391
+ return m ? m[0] : def;
17392
+ }, "fn");
17393
+ option.default(defaultValue).argParser(fn);
17394
+ } else {
17395
+ option.default(fn);
17396
+ }
17397
+ return this.addOption(option);
17398
+ }
17399
+ /**
17400
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
17401
+ *
17402
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
17403
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
17404
+ *
17405
+ * See the README for more details, and see also addOption() and requiredOption().
17406
+ *
17407
+ * @example
17408
+ * program
17409
+ * .option('-p, --pepper', 'add pepper')
17410
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
17411
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
17412
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
17413
+ *
17414
+ * @param {string} flags
17415
+ * @param {string} [description]
17416
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
17417
+ * @param {*} [defaultValue]
17418
+ * @return {Command} `this` command for chaining
17419
+ */
17420
+ option(flags, description, parseArg, defaultValue) {
17421
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
17422
+ }
17423
+ /**
17424
+ * Add a required option which must have a value after parsing. This usually means
17425
+ * the option must be specified on the command line. (Otherwise the same as .option().)
17426
+ *
17427
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
17428
+ *
17429
+ * @param {string} flags
17430
+ * @param {string} [description]
17431
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
17432
+ * @param {*} [defaultValue]
17433
+ * @return {Command} `this` command for chaining
17434
+ */
17435
+ requiredOption(flags, description, parseArg, defaultValue) {
17436
+ return this._optionEx(
17437
+ { mandatory: true },
17438
+ flags,
17439
+ description,
17440
+ parseArg,
17441
+ defaultValue
17442
+ );
17443
+ }
17444
+ /**
17445
+ * Alter parsing of short flags with optional values.
17446
+ *
17447
+ * @example
17448
+ * // for `.option('-f,--flag [value]'):
17449
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
17450
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
17451
+ *
17452
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
17453
+ * @return {Command} `this` command for chaining
17454
+ */
17455
+ combineFlagAndOptionalValue(combine = true) {
17456
+ this._combineFlagAndOptionalValue = !!combine;
17457
+ return this;
17458
+ }
17459
+ /**
17460
+ * Allow unknown options on the command line.
17461
+ *
17462
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
17463
+ * @return {Command} `this` command for chaining
17464
+ */
17465
+ allowUnknownOption(allowUnknown = true) {
17466
+ this._allowUnknownOption = !!allowUnknown;
17467
+ return this;
17468
+ }
17469
+ /**
17470
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
17471
+ *
17472
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
17473
+ * @return {Command} `this` command for chaining
17474
+ */
17475
+ allowExcessArguments(allowExcess = true) {
17476
+ this._allowExcessArguments = !!allowExcess;
17477
+ return this;
17478
+ }
17479
+ /**
17480
+ * Enable positional options. Positional means global options are specified before subcommands which lets
17481
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
17482
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
17483
+ *
17484
+ * @param {boolean} [positional]
17485
+ * @return {Command} `this` command for chaining
17486
+ */
17487
+ enablePositionalOptions(positional = true) {
17488
+ this._enablePositionalOptions = !!positional;
17489
+ return this;
17490
+ }
17491
+ /**
17492
+ * Pass through options that come after command-arguments rather than treat them as command-options,
17493
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
17494
+ * positional options to have been enabled on the program (parent commands).
17495
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
17496
+ *
17497
+ * @param {boolean} [passThrough] for unknown options.
17498
+ * @return {Command} `this` command for chaining
17499
+ */
17500
+ passThroughOptions(passThrough = true) {
17501
+ this._passThroughOptions = !!passThrough;
17502
+ this._checkForBrokenPassThrough();
17503
+ return this;
17504
+ }
17505
+ /**
17506
+ * @private
17507
+ */
17508
+ _checkForBrokenPassThrough() {
17509
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
17510
+ throw new Error(
17511
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
17512
+ );
17513
+ }
17514
+ }
17515
+ /**
17516
+ * Whether to store option values as properties on command object,
17517
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
17518
+ *
17519
+ * @param {boolean} [storeAsProperties=true]
17520
+ * @return {Command} `this` command for chaining
17521
+ */
17522
+ storeOptionsAsProperties(storeAsProperties = true) {
17523
+ if (this.options.length) {
17524
+ throw new Error("call .storeOptionsAsProperties() before adding options");
17525
+ }
17526
+ if (Object.keys(this._optionValues).length) {
17527
+ throw new Error(
17528
+ "call .storeOptionsAsProperties() before setting option values"
17529
+ );
17530
+ }
17531
+ this._storeOptionsAsProperties = !!storeAsProperties;
17532
+ return this;
17533
+ }
17534
+ /**
17535
+ * Retrieve option value.
17536
+ *
17537
+ * @param {string} key
17538
+ * @return {object} value
17539
+ */
17540
+ getOptionValue(key) {
17541
+ if (this._storeOptionsAsProperties) {
17542
+ return this[key];
17543
+ }
17544
+ return this._optionValues[key];
17545
+ }
17546
+ /**
17547
+ * Store option value.
17548
+ *
17549
+ * @param {string} key
17550
+ * @param {object} value
17551
+ * @return {Command} `this` command for chaining
17552
+ */
17553
+ setOptionValue(key, value) {
17554
+ return this.setOptionValueWithSource(key, value, void 0);
17555
+ }
17556
+ /**
17557
+ * Store option value and where the value came from.
17558
+ *
17559
+ * @param {string} key
17560
+ * @param {object} value
17561
+ * @param {string} source - expected values are default/config/env/cli/implied
17562
+ * @return {Command} `this` command for chaining
17563
+ */
17564
+ setOptionValueWithSource(key, value, source) {
17565
+ if (this._storeOptionsAsProperties) {
17566
+ this[key] = value;
17567
+ } else {
17568
+ this._optionValues[key] = value;
17569
+ }
17570
+ this._optionValueSources[key] = source;
17571
+ return this;
17572
+ }
17573
+ /**
17574
+ * Get source of option value.
17575
+ * Expected values are default | config | env | cli | implied
17576
+ *
17577
+ * @param {string} key
17578
+ * @return {string}
17579
+ */
17580
+ getOptionValueSource(key) {
17581
+ return this._optionValueSources[key];
17582
+ }
17583
+ /**
17584
+ * Get source of option value. See also .optsWithGlobals().
17585
+ * Expected values are default | config | env | cli | implied
17586
+ *
17587
+ * @param {string} key
17588
+ * @return {string}
17589
+ */
17590
+ getOptionValueSourceWithGlobals(key) {
17591
+ let source;
17592
+ this._getCommandAndAncestors().forEach((cmd) => {
17593
+ if (cmd.getOptionValueSource(key) !== void 0) {
17594
+ source = cmd.getOptionValueSource(key);
17595
+ }
17596
+ });
17597
+ return source;
17598
+ }
17599
+ /**
17600
+ * Get user arguments from implied or explicit arguments.
17601
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
17602
+ *
17603
+ * @private
17604
+ */
17605
+ _prepareUserArgs(argv, parseOptions) {
17606
+ if (argv !== void 0 && !Array.isArray(argv)) {
17607
+ throw new Error("first parameter to parse must be array or undefined");
17608
+ }
17609
+ parseOptions = parseOptions || {};
17610
+ if (argv === void 0 && parseOptions.from === void 0) {
17611
+ if (process2.versions?.electron) {
17612
+ parseOptions.from = "electron";
17613
+ }
17614
+ const execArgv = process2.execArgv ?? [];
17615
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
17616
+ parseOptions.from = "eval";
17617
+ }
17618
+ }
17619
+ if (argv === void 0) {
17620
+ argv = process2.argv;
17621
+ }
17622
+ this.rawArgs = argv.slice();
17623
+ let userArgs;
17624
+ switch (parseOptions.from) {
17625
+ case void 0:
17626
+ case "node":
17627
+ this._scriptPath = argv[1];
17628
+ userArgs = argv.slice(2);
17629
+ break;
17630
+ case "electron":
17631
+ if (process2.defaultApp) {
17632
+ this._scriptPath = argv[1];
17633
+ userArgs = argv.slice(2);
17634
+ } else {
17635
+ userArgs = argv.slice(1);
17636
+ }
17637
+ break;
17638
+ case "user":
17639
+ userArgs = argv.slice(0);
17640
+ break;
17641
+ case "eval":
17642
+ userArgs = argv.slice(1);
17643
+ break;
17644
+ default:
17645
+ throw new Error(
17646
+ `unexpected parse option { from: '${parseOptions.from}' }`
17647
+ );
17648
+ }
17649
+ if (!this._name && this._scriptPath)
17650
+ this.nameFromFilename(this._scriptPath);
17651
+ this._name = this._name || "program";
17652
+ return userArgs;
17653
+ }
17654
+ /**
17655
+ * Parse `argv`, setting options and invoking commands when defined.
17656
+ *
17657
+ * Use parseAsync instead of parse if any of your action handlers are async.
17658
+ *
17659
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
17660
+ *
17661
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
17662
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
17663
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
17664
+ * - `'user'`: just user arguments
17665
+ *
17666
+ * @example
17667
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
17668
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
17669
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
17670
+ *
17671
+ * @param {string[]} [argv] - optional, defaults to process.argv
17672
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
17673
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
17674
+ * @return {Command} `this` command for chaining
17675
+ */
17676
+ parse(argv, parseOptions) {
17677
+ this._prepareForParse();
17678
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
17679
+ this._parseCommand([], userArgs);
17680
+ return this;
17681
+ }
17682
+ /**
17683
+ * Parse `argv`, setting options and invoking commands when defined.
17684
+ *
17685
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
17686
+ *
17687
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
17688
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
17689
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
17690
+ * - `'user'`: just user arguments
17691
+ *
17692
+ * @example
17693
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
17694
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
17695
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
17696
+ *
17697
+ * @param {string[]} [argv]
17698
+ * @param {object} [parseOptions]
17699
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
17700
+ * @return {Promise}
17701
+ */
17702
+ async parseAsync(argv, parseOptions) {
17703
+ this._prepareForParse();
17704
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
17705
+ await this._parseCommand([], userArgs);
17706
+ return this;
17707
+ }
17708
+ _prepareForParse() {
17709
+ if (this._savedState === null) {
17710
+ this.saveStateBeforeParse();
17711
+ } else {
17712
+ this.restoreStateBeforeParse();
17713
+ }
17714
+ }
17715
+ /**
17716
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
17717
+ * Not usually called directly, but available for subclasses to save their custom state.
17718
+ *
17719
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
17720
+ */
17721
+ saveStateBeforeParse() {
17722
+ this._savedState = {
17723
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
17724
+ _name: this._name,
17725
+ // option values before parse have default values (including false for negated options)
17726
+ // shallow clones
17727
+ _optionValues: { ...this._optionValues },
17728
+ _optionValueSources: { ...this._optionValueSources }
17729
+ };
17730
+ }
17731
+ /**
17732
+ * Restore state before parse for calls after the first.
17733
+ * Not usually called directly, but available for subclasses to save their custom state.
17734
+ *
17735
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
17736
+ */
17737
+ restoreStateBeforeParse() {
17738
+ if (this._storeOptionsAsProperties)
17739
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17740
+ - either make a new Command for each call to parse, or stop storing options as properties`);
17741
+ this._name = this._savedState._name;
17742
+ this._scriptPath = null;
17743
+ this.rawArgs = [];
17744
+ this._optionValues = { ...this._savedState._optionValues };
17745
+ this._optionValueSources = { ...this._savedState._optionValueSources };
17746
+ this.args = [];
17747
+ this.processedArgs = [];
17748
+ }
17749
+ /**
17750
+ * Throw if expected executable is missing. Add lots of help for author.
17751
+ *
17752
+ * @param {string} executableFile
17753
+ * @param {string} executableDir
17754
+ * @param {string} subcommandName
17755
+ */
17756
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
17757
+ if (fs3.existsSync(executableFile)) return;
17758
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
17759
+ const executableMissing = `'${executableFile}' does not exist
17760
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17761
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17762
+ - ${executableDirMessage}`;
17763
+ throw new Error(executableMissing);
17764
+ }
17765
+ /**
17766
+ * Execute a sub-command executable.
17767
+ *
17768
+ * @private
17769
+ */
17770
+ _executeSubCommand(subcommand, args) {
17771
+ args = args.slice();
17772
+ let launchWithNode = false;
17773
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
17774
+ function findFile(baseDir, baseName) {
17775
+ const localBin = path5.resolve(baseDir, baseName);
17776
+ if (fs3.existsSync(localBin)) return localBin;
17777
+ if (sourceExt.includes(path5.extname(baseName))) return void 0;
17778
+ const foundExt = sourceExt.find(
17779
+ (ext) => fs3.existsSync(`${localBin}${ext}`)
17780
+ );
17781
+ if (foundExt) return `${localBin}${foundExt}`;
17782
+ return void 0;
17783
+ }
17784
+ __name(findFile, "findFile");
17785
+ this._checkForMissingMandatoryOptions();
17786
+ this._checkForConflictingOptions();
17787
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
17788
+ let executableDir = this._executableDir || "";
17789
+ if (this._scriptPath) {
17790
+ let resolvedScriptPath;
17791
+ try {
17792
+ resolvedScriptPath = fs3.realpathSync(this._scriptPath);
17793
+ } catch {
17794
+ resolvedScriptPath = this._scriptPath;
17795
+ }
17796
+ executableDir = path5.resolve(
17797
+ path5.dirname(resolvedScriptPath),
17798
+ executableDir
17799
+ );
17800
+ }
17801
+ if (executableDir) {
17802
+ let localFile = findFile(executableDir, executableFile);
17803
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
17804
+ const legacyName = path5.basename(
17805
+ this._scriptPath,
17806
+ path5.extname(this._scriptPath)
17807
+ );
17808
+ if (legacyName !== this._name) {
17809
+ localFile = findFile(
17810
+ executableDir,
17811
+ `${legacyName}-${subcommand._name}`
17812
+ );
17813
+ }
17814
+ }
17815
+ executableFile = localFile || executableFile;
17816
+ }
17817
+ launchWithNode = sourceExt.includes(path5.extname(executableFile));
17818
+ let proc;
17819
+ if (process2.platform !== "win32") {
17820
+ if (launchWithNode) {
17821
+ args.unshift(executableFile);
17822
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
17823
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
17824
+ } else {
17825
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
17826
+ }
17827
+ } else {
17828
+ this._checkForMissingExecutable(
17829
+ executableFile,
17830
+ executableDir,
17831
+ subcommand._name
17832
+ );
17833
+ args.unshift(executableFile);
17834
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
17835
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
17836
+ }
17837
+ if (!proc.killed) {
17838
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
17839
+ signals.forEach((signal) => {
17840
+ process2.on(signal, () => {
17841
+ if (proc.killed === false && proc.exitCode === null) {
17842
+ proc.kill(signal);
17843
+ }
17844
+ });
17845
+ });
17846
+ }
17847
+ const exitCallback = this._exitCallback;
17848
+ proc.on("close", (code) => {
17849
+ code = code ?? 1;
17850
+ if (!exitCallback) {
17851
+ process2.exit(code);
17852
+ } else {
17853
+ exitCallback(
17854
+ new CommanderError2(
17855
+ code,
17856
+ "commander.executeSubCommandAsync",
17857
+ "(close)"
17858
+ )
17859
+ );
17860
+ }
17861
+ });
17862
+ proc.on("error", (err) => {
17863
+ if (err.code === "ENOENT") {
17864
+ this._checkForMissingExecutable(
17865
+ executableFile,
17866
+ executableDir,
17867
+ subcommand._name
17868
+ );
17869
+ } else if (err.code === "EACCES") {
17870
+ throw new Error(`'${executableFile}' not executable`);
17871
+ }
17872
+ if (!exitCallback) {
17873
+ process2.exit(1);
17874
+ } else {
17875
+ const wrappedError = new CommanderError2(
17876
+ 1,
17877
+ "commander.executeSubCommandAsync",
17878
+ "(error)"
17879
+ );
17880
+ wrappedError.nestedError = err;
17881
+ exitCallback(wrappedError);
17882
+ }
17883
+ });
17884
+ this.runningCommand = proc;
17885
+ }
17886
+ /**
17887
+ * @private
17888
+ */
17889
+ _dispatchSubcommand(commandName, operands, unknown) {
17890
+ const subCommand = this._findCommand(commandName);
17891
+ if (!subCommand) this.help({ error: true });
17892
+ subCommand._prepareForParse();
17893
+ let promiseChain;
17894
+ promiseChain = this._chainOrCallSubCommandHook(
17895
+ promiseChain,
17896
+ subCommand,
17897
+ "preSubcommand"
17898
+ );
17899
+ promiseChain = this._chainOrCall(promiseChain, () => {
17900
+ if (subCommand._executableHandler) {
17901
+ this._executeSubCommand(subCommand, operands.concat(unknown));
17902
+ } else {
17903
+ return subCommand._parseCommand(operands, unknown);
17904
+ }
17905
+ });
17906
+ return promiseChain;
17907
+ }
17908
+ /**
17909
+ * Invoke help directly if possible, or dispatch if necessary.
17910
+ * e.g. help foo
17911
+ *
17912
+ * @private
17913
+ */
17914
+ _dispatchHelpCommand(subcommandName) {
17915
+ if (!subcommandName) {
17916
+ this.help();
17917
+ }
17918
+ const subCommand = this._findCommand(subcommandName);
17919
+ if (subCommand && !subCommand._executableHandler) {
17920
+ subCommand.help();
17921
+ }
17922
+ return this._dispatchSubcommand(
17923
+ subcommandName,
17924
+ [],
17925
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
17926
+ );
17927
+ }
17928
+ /**
17929
+ * Check this.args against expected this.registeredArguments.
17930
+ *
17931
+ * @private
17932
+ */
17933
+ _checkNumberOfArguments() {
17934
+ this.registeredArguments.forEach((arg, i) => {
17935
+ if (arg.required && this.args[i] == null) {
17936
+ this.missingArgument(arg.name());
17937
+ }
17938
+ });
17939
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
17940
+ return;
17941
+ }
17942
+ if (this.args.length > this.registeredArguments.length) {
17943
+ this._excessArguments(this.args);
17944
+ }
17945
+ }
17946
+ /**
17947
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
17948
+ *
17949
+ * @private
17950
+ */
17951
+ _processArguments() {
17952
+ const myParseArg = /* @__PURE__ */ __name((argument, value, previous) => {
17953
+ let parsedValue = value;
17954
+ if (value !== null && argument.parseArg) {
17955
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
17956
+ parsedValue = this._callParseArg(
17957
+ argument,
17958
+ value,
17959
+ previous,
17960
+ invalidValueMessage
17961
+ );
17962
+ }
17963
+ return parsedValue;
17964
+ }, "myParseArg");
17965
+ this._checkNumberOfArguments();
17966
+ const processedArgs = [];
17967
+ this.registeredArguments.forEach((declaredArg, index) => {
17968
+ let value = declaredArg.defaultValue;
17969
+ if (declaredArg.variadic) {
17970
+ if (index < this.args.length) {
17971
+ value = this.args.slice(index);
17972
+ if (declaredArg.parseArg) {
17973
+ value = value.reduce((processed, v) => {
17974
+ return myParseArg(declaredArg, v, processed);
17975
+ }, declaredArg.defaultValue);
17976
+ }
17977
+ } else if (value === void 0) {
17978
+ value = [];
17979
+ }
17980
+ } else if (index < this.args.length) {
17981
+ value = this.args[index];
17982
+ if (declaredArg.parseArg) {
17983
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
17984
+ }
17985
+ }
17986
+ processedArgs[index] = value;
17987
+ });
17988
+ this.processedArgs = processedArgs;
17989
+ }
17990
+ /**
17991
+ * Once we have a promise we chain, but call synchronously until then.
17992
+ *
17993
+ * @param {(Promise|undefined)} promise
17994
+ * @param {Function} fn
17995
+ * @return {(Promise|undefined)}
17996
+ * @private
17997
+ */
17998
+ _chainOrCall(promise, fn) {
17999
+ if (promise && promise.then && typeof promise.then === "function") {
18000
+ return promise.then(() => fn());
18001
+ }
18002
+ return fn();
18003
+ }
18004
+ /**
18005
+ *
18006
+ * @param {(Promise|undefined)} promise
18007
+ * @param {string} event
18008
+ * @return {(Promise|undefined)}
18009
+ * @private
18010
+ */
18011
+ _chainOrCallHooks(promise, event) {
18012
+ let result = promise;
18013
+ const hooks = [];
18014
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
18015
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
18016
+ hooks.push({ hookedCommand, callback });
18017
+ });
18018
+ });
18019
+ if (event === "postAction") {
18020
+ hooks.reverse();
18021
+ }
18022
+ hooks.forEach((hookDetail) => {
18023
+ result = this._chainOrCall(result, () => {
18024
+ return hookDetail.callback(hookDetail.hookedCommand, this);
18025
+ });
18026
+ });
18027
+ return result;
18028
+ }
18029
+ /**
18030
+ *
18031
+ * @param {(Promise|undefined)} promise
18032
+ * @param {Command} subCommand
18033
+ * @param {string} event
18034
+ * @return {(Promise|undefined)}
18035
+ * @private
18036
+ */
18037
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
18038
+ let result = promise;
18039
+ if (this._lifeCycleHooks[event] !== void 0) {
18040
+ this._lifeCycleHooks[event].forEach((hook) => {
18041
+ result = this._chainOrCall(result, () => {
18042
+ return hook(this, subCommand);
18043
+ });
18044
+ });
18045
+ }
18046
+ return result;
18047
+ }
18048
+ /**
18049
+ * Process arguments in context of this command.
18050
+ * Returns action result, in case it is a promise.
18051
+ *
18052
+ * @private
18053
+ */
18054
+ _parseCommand(operands, unknown) {
18055
+ const parsed = this.parseOptions(unknown);
18056
+ this._parseOptionsEnv();
18057
+ this._parseOptionsImplied();
18058
+ operands = operands.concat(parsed.operands);
18059
+ unknown = parsed.unknown;
18060
+ this.args = operands.concat(unknown);
18061
+ if (operands && this._findCommand(operands[0])) {
18062
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
18063
+ }
18064
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
18065
+ return this._dispatchHelpCommand(operands[1]);
18066
+ }
18067
+ if (this._defaultCommandName) {
18068
+ this._outputHelpIfRequested(unknown);
18069
+ return this._dispatchSubcommand(
18070
+ this._defaultCommandName,
18071
+ operands,
18072
+ unknown
18073
+ );
18074
+ }
18075
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
18076
+ this.help({ error: true });
18077
+ }
18078
+ this._outputHelpIfRequested(parsed.unknown);
18079
+ this._checkForMissingMandatoryOptions();
18080
+ this._checkForConflictingOptions();
18081
+ const checkForUnknownOptions = /* @__PURE__ */ __name(() => {
18082
+ if (parsed.unknown.length > 0) {
18083
+ this.unknownOption(parsed.unknown[0]);
18084
+ }
18085
+ }, "checkForUnknownOptions");
18086
+ const commandEvent = `command:${this.name()}`;
18087
+ if (this._actionHandler) {
18088
+ checkForUnknownOptions();
18089
+ this._processArguments();
18090
+ let promiseChain;
18091
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
18092
+ promiseChain = this._chainOrCall(
18093
+ promiseChain,
18094
+ () => this._actionHandler(this.processedArgs)
18095
+ );
18096
+ if (this.parent) {
18097
+ promiseChain = this._chainOrCall(promiseChain, () => {
18098
+ this.parent.emit(commandEvent, operands, unknown);
18099
+ });
18100
+ }
18101
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
18102
+ return promiseChain;
18103
+ }
18104
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
18105
+ checkForUnknownOptions();
18106
+ this._processArguments();
18107
+ this.parent.emit(commandEvent, operands, unknown);
18108
+ } else if (operands.length) {
18109
+ if (this._findCommand("*")) {
18110
+ return this._dispatchSubcommand("*", operands, unknown);
18111
+ }
18112
+ if (this.listenerCount("command:*")) {
18113
+ this.emit("command:*", operands, unknown);
18114
+ } else if (this.commands.length) {
18115
+ this.unknownCommand();
18116
+ } else {
18117
+ checkForUnknownOptions();
18118
+ this._processArguments();
18119
+ }
18120
+ } else if (this.commands.length) {
18121
+ checkForUnknownOptions();
18122
+ this.help({ error: true });
18123
+ } else {
18124
+ checkForUnknownOptions();
18125
+ this._processArguments();
18126
+ }
18127
+ }
18128
+ /**
18129
+ * Find matching command.
18130
+ *
18131
+ * @private
18132
+ * @return {Command | undefined}
18133
+ */
18134
+ _findCommand(name) {
18135
+ if (!name) return void 0;
18136
+ return this.commands.find(
18137
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
18138
+ );
18139
+ }
18140
+ /**
18141
+ * Return an option matching `arg` if any.
18142
+ *
18143
+ * @param {string} arg
18144
+ * @return {Option}
18145
+ * @package
18146
+ */
18147
+ _findOption(arg) {
18148
+ return this.options.find((option) => option.is(arg));
18149
+ }
18150
+ /**
18151
+ * Display an error message if a mandatory option does not have a value.
18152
+ * Called after checking for help flags in leaf subcommand.
18153
+ *
18154
+ * @private
18155
+ */
18156
+ _checkForMissingMandatoryOptions() {
18157
+ this._getCommandAndAncestors().forEach((cmd) => {
18158
+ cmd.options.forEach((anOption) => {
18159
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
18160
+ cmd.missingMandatoryOptionValue(anOption);
18161
+ }
18162
+ });
18163
+ });
18164
+ }
18165
+ /**
18166
+ * Display an error message if conflicting options are used together in this.
18167
+ *
18168
+ * @private
18169
+ */
18170
+ _checkForConflictingLocalOptions() {
18171
+ const definedNonDefaultOptions = this.options.filter((option) => {
18172
+ const optionKey = option.attributeName();
18173
+ if (this.getOptionValue(optionKey) === void 0) {
18174
+ return false;
18175
+ }
18176
+ return this.getOptionValueSource(optionKey) !== "default";
18177
+ });
18178
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
18179
+ (option) => option.conflictsWith.length > 0
18180
+ );
18181
+ optionsWithConflicting.forEach((option) => {
18182
+ const conflictingAndDefined = definedNonDefaultOptions.find(
18183
+ (defined) => option.conflictsWith.includes(defined.attributeName())
18184
+ );
18185
+ if (conflictingAndDefined) {
18186
+ this._conflictingOption(option, conflictingAndDefined);
18187
+ }
18188
+ });
18189
+ }
18190
+ /**
18191
+ * Display an error message if conflicting options are used together.
18192
+ * Called after checking for help flags in leaf subcommand.
18193
+ *
18194
+ * @private
18195
+ */
18196
+ _checkForConflictingOptions() {
18197
+ this._getCommandAndAncestors().forEach((cmd) => {
18198
+ cmd._checkForConflictingLocalOptions();
18199
+ });
18200
+ }
18201
+ /**
18202
+ * Parse options from `argv` removing known options,
18203
+ * and return argv split into operands and unknown arguments.
18204
+ *
18205
+ * Side effects: modifies command by storing options. Does not reset state if called again.
18206
+ *
18207
+ * Examples:
18208
+ *
18209
+ * argv => operands, unknown
18210
+ * --known kkk op => [op], []
18211
+ * op --known kkk => [op], []
18212
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
18213
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
18214
+ *
18215
+ * @param {string[]} argv
18216
+ * @return {{operands: string[], unknown: string[]}}
18217
+ */
18218
+ parseOptions(argv) {
18219
+ const operands = [];
18220
+ const unknown = [];
18221
+ let dest = operands;
18222
+ const args = argv.slice();
18223
+ function maybeOption(arg) {
18224
+ return arg.length > 1 && arg[0] === "-";
18225
+ }
18226
+ __name(maybeOption, "maybeOption");
18227
+ let activeVariadicOption = null;
18228
+ while (args.length) {
18229
+ const arg = args.shift();
18230
+ if (arg === "--") {
18231
+ if (dest === unknown) dest.push(arg);
18232
+ dest.push(...args);
18233
+ break;
18234
+ }
18235
+ if (activeVariadicOption && !maybeOption(arg)) {
18236
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
18237
+ continue;
18238
+ }
18239
+ activeVariadicOption = null;
18240
+ if (maybeOption(arg)) {
18241
+ const option = this._findOption(arg);
18242
+ if (option) {
18243
+ if (option.required) {
18244
+ const value = args.shift();
18245
+ if (value === void 0) this.optionMissingArgument(option);
18246
+ this.emit(`option:${option.name()}`, value);
18247
+ } else if (option.optional) {
18248
+ let value = null;
18249
+ if (args.length > 0 && !maybeOption(args[0])) {
18250
+ value = args.shift();
18251
+ }
18252
+ this.emit(`option:${option.name()}`, value);
18253
+ } else {
18254
+ this.emit(`option:${option.name()}`);
18255
+ }
18256
+ activeVariadicOption = option.variadic ? option : null;
18257
+ continue;
18258
+ }
18259
+ }
18260
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
18261
+ const option = this._findOption(`-${arg[1]}`);
18262
+ if (option) {
18263
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
18264
+ this.emit(`option:${option.name()}`, arg.slice(2));
18265
+ } else {
18266
+ this.emit(`option:${option.name()}`);
18267
+ args.unshift(`-${arg.slice(2)}`);
18268
+ }
18269
+ continue;
18270
+ }
18271
+ }
18272
+ if (/^--[^=]+=/.test(arg)) {
18273
+ const index = arg.indexOf("=");
18274
+ const option = this._findOption(arg.slice(0, index));
18275
+ if (option && (option.required || option.optional)) {
18276
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
18277
+ continue;
18278
+ }
18279
+ }
18280
+ if (maybeOption(arg)) {
18281
+ dest = unknown;
18282
+ }
18283
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
18284
+ if (this._findCommand(arg)) {
18285
+ operands.push(arg);
18286
+ if (args.length > 0) unknown.push(...args);
18287
+ break;
18288
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
18289
+ operands.push(arg);
18290
+ if (args.length > 0) operands.push(...args);
18291
+ break;
18292
+ } else if (this._defaultCommandName) {
18293
+ unknown.push(arg);
18294
+ if (args.length > 0) unknown.push(...args);
18295
+ break;
18296
+ }
18297
+ }
18298
+ if (this._passThroughOptions) {
18299
+ dest.push(arg);
18300
+ if (args.length > 0) dest.push(...args);
18301
+ break;
18302
+ }
18303
+ dest.push(arg);
18304
+ }
18305
+ return { operands, unknown };
18306
+ }
18307
+ /**
18308
+ * Return an object containing local option values as key-value pairs.
18309
+ *
18310
+ * @return {object}
18311
+ */
18312
+ opts() {
18313
+ if (this._storeOptionsAsProperties) {
18314
+ const result = {};
18315
+ const len = this.options.length;
18316
+ for (let i = 0; i < len; i++) {
18317
+ const key = this.options[i].attributeName();
18318
+ result[key] = key === this._versionOptionName ? this._version : this[key];
18319
+ }
18320
+ return result;
18321
+ }
18322
+ return this._optionValues;
18323
+ }
18324
+ /**
18325
+ * Return an object containing merged local and global option values as key-value pairs.
18326
+ *
18327
+ * @return {object}
18328
+ */
18329
+ optsWithGlobals() {
18330
+ return this._getCommandAndAncestors().reduce(
18331
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
18332
+ {}
18333
+ );
18334
+ }
18335
+ /**
18336
+ * Display error message and exit (or call exitOverride).
18337
+ *
18338
+ * @param {string} message
18339
+ * @param {object} [errorOptions]
18340
+ * @param {string} [errorOptions.code] - an id string representing the error
18341
+ * @param {number} [errorOptions.exitCode] - used with process.exit
18342
+ */
18343
+ error(message, errorOptions) {
18344
+ this._outputConfiguration.outputError(
18345
+ `${message}
18346
+ `,
18347
+ this._outputConfiguration.writeErr
18348
+ );
18349
+ if (typeof this._showHelpAfterError === "string") {
18350
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
18351
+ `);
18352
+ } else if (this._showHelpAfterError) {
18353
+ this._outputConfiguration.writeErr("\n");
18354
+ this.outputHelp({ error: true });
18355
+ }
18356
+ const config = errorOptions || {};
18357
+ const exitCode = config.exitCode || 1;
18358
+ const code = config.code || "commander.error";
18359
+ this._exit(exitCode, code, message);
18360
+ }
18361
+ /**
18362
+ * Apply any option related environment variables, if option does
18363
+ * not have a value from cli or client code.
18364
+ *
18365
+ * @private
18366
+ */
18367
+ _parseOptionsEnv() {
18368
+ this.options.forEach((option) => {
18369
+ if (option.envVar && option.envVar in process2.env) {
18370
+ const optionKey = option.attributeName();
18371
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
18372
+ this.getOptionValueSource(optionKey)
18373
+ )) {
18374
+ if (option.required || option.optional) {
18375
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
18376
+ } else {
18377
+ this.emit(`optionEnv:${option.name()}`);
18378
+ }
18379
+ }
18380
+ }
18381
+ });
18382
+ }
18383
+ /**
18384
+ * Apply any implied option values, if option is undefined or default value.
18385
+ *
18386
+ * @private
18387
+ */
18388
+ _parseOptionsImplied() {
18389
+ const dualHelper = new DualOptions(this.options);
18390
+ const hasCustomOptionValue = /* @__PURE__ */ __name((optionKey) => {
18391
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
18392
+ }, "hasCustomOptionValue");
18393
+ this.options.filter(
18394
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
18395
+ this.getOptionValue(option.attributeName()),
18396
+ option
18397
+ )
18398
+ ).forEach((option) => {
18399
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
18400
+ this.setOptionValueWithSource(
18401
+ impliedKey,
18402
+ option.implied[impliedKey],
18403
+ "implied"
18404
+ );
18405
+ });
18406
+ });
18407
+ }
18408
+ /**
18409
+ * Argument `name` is missing.
18410
+ *
18411
+ * @param {string} name
18412
+ * @private
18413
+ */
18414
+ missingArgument(name) {
18415
+ const message = `error: missing required argument '${name}'`;
18416
+ this.error(message, { code: "commander.missingArgument" });
18417
+ }
18418
+ /**
18419
+ * `Option` is missing an argument.
18420
+ *
18421
+ * @param {Option} option
18422
+ * @private
18423
+ */
18424
+ optionMissingArgument(option) {
18425
+ const message = `error: option '${option.flags}' argument missing`;
18426
+ this.error(message, { code: "commander.optionMissingArgument" });
18427
+ }
18428
+ /**
18429
+ * `Option` does not have a value, and is a mandatory option.
18430
+ *
18431
+ * @param {Option} option
18432
+ * @private
18433
+ */
18434
+ missingMandatoryOptionValue(option) {
18435
+ const message = `error: required option '${option.flags}' not specified`;
18436
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
18437
+ }
18438
+ /**
18439
+ * `Option` conflicts with another option.
18440
+ *
18441
+ * @param {Option} option
18442
+ * @param {Option} conflictingOption
18443
+ * @private
18444
+ */
18445
+ _conflictingOption(option, conflictingOption) {
18446
+ const findBestOptionFromValue = /* @__PURE__ */ __name((option2) => {
18447
+ const optionKey = option2.attributeName();
18448
+ const optionValue = this.getOptionValue(optionKey);
18449
+ const negativeOption = this.options.find(
18450
+ (target) => target.negate && optionKey === target.attributeName()
18451
+ );
18452
+ const positiveOption = this.options.find(
18453
+ (target) => !target.negate && optionKey === target.attributeName()
18454
+ );
18455
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
18456
+ return negativeOption;
18457
+ }
18458
+ return positiveOption || option2;
18459
+ }, "findBestOptionFromValue");
18460
+ const getErrorMessage = /* @__PURE__ */ __name((option2) => {
18461
+ const bestOption = findBestOptionFromValue(option2);
18462
+ const optionKey = bestOption.attributeName();
18463
+ const source = this.getOptionValueSource(optionKey);
18464
+ if (source === "env") {
18465
+ return `environment variable '${bestOption.envVar}'`;
18466
+ }
18467
+ return `option '${bestOption.flags}'`;
18468
+ }, "getErrorMessage");
18469
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
18470
+ this.error(message, { code: "commander.conflictingOption" });
18471
+ }
18472
+ /**
18473
+ * Unknown option `flag`.
18474
+ *
18475
+ * @param {string} flag
18476
+ * @private
18477
+ */
18478
+ unknownOption(flag) {
18479
+ if (this._allowUnknownOption) return;
18480
+ let suggestion = "";
18481
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
18482
+ let candidateFlags = [];
18483
+ let command = this;
18484
+ do {
18485
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
18486
+ candidateFlags = candidateFlags.concat(moreFlags);
18487
+ command = command.parent;
18488
+ } while (command && !command._enablePositionalOptions);
18489
+ suggestion = suggestSimilar(flag, candidateFlags);
18490
+ }
18491
+ const message = `error: unknown option '${flag}'${suggestion}`;
18492
+ this.error(message, { code: "commander.unknownOption" });
18493
+ }
18494
+ /**
18495
+ * Excess arguments, more than expected.
18496
+ *
18497
+ * @param {string[]} receivedArgs
18498
+ * @private
18499
+ */
18500
+ _excessArguments(receivedArgs) {
18501
+ if (this._allowExcessArguments) return;
18502
+ const expected = this.registeredArguments.length;
18503
+ const s = expected === 1 ? "" : "s";
18504
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
18505
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
18506
+ this.error(message, { code: "commander.excessArguments" });
18507
+ }
18508
+ /**
18509
+ * Unknown command.
18510
+ *
18511
+ * @private
18512
+ */
18513
+ unknownCommand() {
18514
+ const unknownName = this.args[0];
18515
+ let suggestion = "";
18516
+ if (this._showSuggestionAfterError) {
18517
+ const candidateNames = [];
18518
+ this.createHelp().visibleCommands(this).forEach((command) => {
18519
+ candidateNames.push(command.name());
18520
+ if (command.alias()) candidateNames.push(command.alias());
18521
+ });
18522
+ suggestion = suggestSimilar(unknownName, candidateNames);
18523
+ }
18524
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
18525
+ this.error(message, { code: "commander.unknownCommand" });
18526
+ }
18527
+ /**
18528
+ * Get or set the program version.
18529
+ *
18530
+ * This method auto-registers the "-V, --version" option which will print the version number.
18531
+ *
18532
+ * You can optionally supply the flags and description to override the defaults.
18533
+ *
18534
+ * @param {string} [str]
18535
+ * @param {string} [flags]
18536
+ * @param {string} [description]
18537
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
18538
+ */
18539
+ version(str, flags, description) {
18540
+ if (str === void 0) return this._version;
18541
+ this._version = str;
18542
+ flags = flags || "-V, --version";
18543
+ description = description || "output the version number";
18544
+ const versionOption = this.createOption(flags, description);
18545
+ this._versionOptionName = versionOption.attributeName();
18546
+ this._registerOption(versionOption);
18547
+ this.on("option:" + versionOption.name(), () => {
18548
+ this._outputConfiguration.writeOut(`${str}
18549
+ `);
18550
+ this._exit(0, "commander.version", str);
18551
+ });
18552
+ return this;
18553
+ }
18554
+ /**
18555
+ * Set the description.
18556
+ *
18557
+ * @param {string} [str]
18558
+ * @param {object} [argsDescription]
18559
+ * @return {(string|Command)}
18560
+ */
18561
+ description(str, argsDescription) {
18562
+ if (str === void 0 && argsDescription === void 0)
18563
+ return this._description;
18564
+ this._description = str;
18565
+ if (argsDescription) {
18566
+ this._argsDescription = argsDescription;
18567
+ }
18568
+ return this;
18569
+ }
18570
+ /**
18571
+ * Set the summary. Used when listed as subcommand of parent.
18572
+ *
18573
+ * @param {string} [str]
18574
+ * @return {(string|Command)}
18575
+ */
18576
+ summary(str) {
18577
+ if (str === void 0) return this._summary;
18578
+ this._summary = str;
18579
+ return this;
18580
+ }
18581
+ /**
18582
+ * Set an alias for the command.
18583
+ *
18584
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
18585
+ *
18586
+ * @param {string} [alias]
18587
+ * @return {(string|Command)}
18588
+ */
18589
+ alias(alias) {
18590
+ if (alias === void 0) return this._aliases[0];
18591
+ let command = this;
18592
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
18593
+ command = this.commands[this.commands.length - 1];
18594
+ }
18595
+ if (alias === command._name)
18596
+ throw new Error("Command alias can't be the same as its name");
18597
+ const matchingCommand = this.parent?._findCommand(alias);
18598
+ if (matchingCommand) {
18599
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
18600
+ throw new Error(
18601
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
18602
+ );
18603
+ }
18604
+ command._aliases.push(alias);
18605
+ return this;
18606
+ }
18607
+ /**
18608
+ * Set aliases for the command.
18609
+ *
18610
+ * Only the first alias is shown in the auto-generated help.
18611
+ *
18612
+ * @param {string[]} [aliases]
18613
+ * @return {(string[]|Command)}
18614
+ */
18615
+ aliases(aliases) {
18616
+ if (aliases === void 0) return this._aliases;
18617
+ aliases.forEach((alias) => this.alias(alias));
18618
+ return this;
18619
+ }
18620
+ /**
18621
+ * Set / get the command usage `str`.
18622
+ *
18623
+ * @param {string} [str]
18624
+ * @return {(string|Command)}
18625
+ */
18626
+ usage(str) {
18627
+ if (str === void 0) {
18628
+ if (this._usage) return this._usage;
18629
+ const args = this.registeredArguments.map((arg) => {
18630
+ return humanReadableArgName(arg);
18631
+ });
18632
+ return [].concat(
18633
+ this.options.length || this._helpOption !== null ? "[options]" : [],
18634
+ this.commands.length ? "[command]" : [],
18635
+ this.registeredArguments.length ? args : []
18636
+ ).join(" ");
18637
+ }
18638
+ this._usage = str;
18639
+ return this;
18640
+ }
18641
+ /**
18642
+ * Get or set the name of the command.
18643
+ *
18644
+ * @param {string} [str]
18645
+ * @return {(string|Command)}
18646
+ */
18647
+ name(str) {
18648
+ if (str === void 0) return this._name;
18649
+ this._name = str;
18650
+ return this;
18651
+ }
18652
+ /**
18653
+ * Set the name of the command from script filename, such as process.argv[1],
18654
+ * or require.main.filename, or __filename.
18655
+ *
18656
+ * (Used internally and public although not documented in README.)
18657
+ *
18658
+ * @example
18659
+ * program.nameFromFilename(require.main.filename);
18660
+ *
18661
+ * @param {string} filename
18662
+ * @return {Command}
18663
+ */
18664
+ nameFromFilename(filename) {
18665
+ this._name = path5.basename(filename, path5.extname(filename));
18666
+ return this;
18667
+ }
18668
+ /**
18669
+ * Get or set the directory for searching for executable subcommands of this command.
18670
+ *
18671
+ * @example
18672
+ * program.executableDir(__dirname);
18673
+ * // or
18674
+ * program.executableDir('subcommands');
18675
+ *
18676
+ * @param {string} [path]
18677
+ * @return {(string|null|Command)}
18678
+ */
18679
+ executableDir(path6) {
18680
+ if (path6 === void 0) return this._executableDir;
18681
+ this._executableDir = path6;
18682
+ return this;
18683
+ }
18684
+ /**
18685
+ * Return program help documentation.
18686
+ *
18687
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
18688
+ * @return {string}
18689
+ */
18690
+ helpInformation(contextOptions) {
18691
+ const helper = this.createHelp();
18692
+ const context = this._getOutputContext(contextOptions);
18693
+ helper.prepareContext({
18694
+ error: context.error,
18695
+ helpWidth: context.helpWidth,
18696
+ outputHasColors: context.hasColors
18697
+ });
18698
+ const text = helper.formatHelp(this, helper);
18699
+ if (context.hasColors) return text;
18700
+ return this._outputConfiguration.stripColor(text);
18701
+ }
18702
+ /**
18703
+ * @typedef HelpContext
18704
+ * @type {object}
18705
+ * @property {boolean} error
18706
+ * @property {number} helpWidth
18707
+ * @property {boolean} hasColors
18708
+ * @property {function} write - includes stripColor if needed
18709
+ *
18710
+ * @returns {HelpContext}
18711
+ * @private
18712
+ */
18713
+ _getOutputContext(contextOptions) {
18714
+ contextOptions = contextOptions || {};
18715
+ const error = !!contextOptions.error;
18716
+ let baseWrite;
18717
+ let hasColors;
18718
+ let helpWidth;
18719
+ if (error) {
18720
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeErr(str), "baseWrite");
18721
+ hasColors = this._outputConfiguration.getErrHasColors();
18722
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
18723
+ } else {
18724
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeOut(str), "baseWrite");
18725
+ hasColors = this._outputConfiguration.getOutHasColors();
18726
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
18727
+ }
18728
+ const write = /* @__PURE__ */ __name((str) => {
18729
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
18730
+ return baseWrite(str);
18731
+ }, "write");
18732
+ return { error, write, hasColors, helpWidth };
18733
+ }
18734
+ /**
18735
+ * Output help information for this command.
18736
+ *
18737
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
18738
+ *
18739
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
18740
+ */
18741
+ outputHelp(contextOptions) {
18742
+ let deprecatedCallback;
18743
+ if (typeof contextOptions === "function") {
18744
+ deprecatedCallback = contextOptions;
18745
+ contextOptions = void 0;
18746
+ }
18747
+ const outputContext = this._getOutputContext(contextOptions);
18748
+ const eventContext = {
18749
+ error: outputContext.error,
18750
+ write: outputContext.write,
18751
+ command: this
18752
+ };
18753
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
18754
+ this.emit("beforeHelp", eventContext);
18755
+ let helpInformation = this.helpInformation({ error: outputContext.error });
18756
+ if (deprecatedCallback) {
18757
+ helpInformation = deprecatedCallback(helpInformation);
18758
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
18759
+ throw new Error("outputHelp callback must return a string or a Buffer");
18760
+ }
18761
+ }
18762
+ outputContext.write(helpInformation);
18763
+ if (this._getHelpOption()?.long) {
18764
+ this.emit(this._getHelpOption().long);
18765
+ }
18766
+ this.emit("afterHelp", eventContext);
18767
+ this._getCommandAndAncestors().forEach(
18768
+ (command) => command.emit("afterAllHelp", eventContext)
18769
+ );
18770
+ }
18771
+ /**
18772
+ * You can pass in flags and a description to customise the built-in help option.
18773
+ * Pass in false to disable the built-in help option.
18774
+ *
18775
+ * @example
18776
+ * program.helpOption('-?, --help' 'show help'); // customise
18777
+ * program.helpOption(false); // disable
18778
+ *
18779
+ * @param {(string | boolean)} flags
18780
+ * @param {string} [description]
18781
+ * @return {Command} `this` command for chaining
18782
+ */
18783
+ helpOption(flags, description) {
18784
+ if (typeof flags === "boolean") {
18785
+ if (flags) {
18786
+ this._helpOption = this._helpOption ?? void 0;
18787
+ } else {
18788
+ this._helpOption = null;
18789
+ }
18790
+ return this;
18791
+ }
18792
+ flags = flags ?? "-h, --help";
18793
+ description = description ?? "display help for command";
18794
+ this._helpOption = this.createOption(flags, description);
18795
+ return this;
18796
+ }
18797
+ /**
18798
+ * Lazy create help option.
18799
+ * Returns null if has been disabled with .helpOption(false).
18800
+ *
18801
+ * @returns {(Option | null)} the help option
18802
+ * @package
18803
+ */
18804
+ _getHelpOption() {
18805
+ if (this._helpOption === void 0) {
18806
+ this.helpOption(void 0, void 0);
18807
+ }
18808
+ return this._helpOption;
18809
+ }
18810
+ /**
18811
+ * Supply your own option to use for the built-in help option.
18812
+ * This is an alternative to using helpOption() to customise the flags and description etc.
18813
+ *
18814
+ * @param {Option} option
18815
+ * @return {Command} `this` command for chaining
18816
+ */
18817
+ addHelpOption(option) {
18818
+ this._helpOption = option;
18819
+ return this;
18820
+ }
18821
+ /**
18822
+ * Output help information and exit.
18823
+ *
18824
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
18825
+ *
18826
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
18827
+ */
18828
+ help(contextOptions) {
18829
+ this.outputHelp(contextOptions);
18830
+ let exitCode = Number(process2.exitCode ?? 0);
18831
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
18832
+ exitCode = 1;
18833
+ }
18834
+ this._exit(exitCode, "commander.help", "(outputHelp)");
18835
+ }
18836
+ /**
18837
+ * // Do a little typing to coordinate emit and listener for the help text events.
18838
+ * @typedef HelpTextEventContext
18839
+ * @type {object}
18840
+ * @property {boolean} error
18841
+ * @property {Command} command
18842
+ * @property {function} write
18843
+ */
18844
+ /**
18845
+ * Add additional text to be displayed with the built-in help.
18846
+ *
18847
+ * Position is 'before' or 'after' to affect just this command,
18848
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
18849
+ *
18850
+ * @param {string} position - before or after built-in help
18851
+ * @param {(string | Function)} text - string to add, or a function returning a string
18852
+ * @return {Command} `this` command for chaining
18853
+ */
18854
+ addHelpText(position, text) {
18855
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
18856
+ if (!allowedValues.includes(position)) {
18857
+ throw new Error(`Unexpected value for position to addHelpText.
18858
+ Expecting one of '${allowedValues.join("', '")}'`);
18859
+ }
18860
+ const helpEvent = `${position}Help`;
18861
+ this.on(helpEvent, (context) => {
18862
+ let helpStr;
18863
+ if (typeof text === "function") {
18864
+ helpStr = text({ error: context.error, command: context.command });
18865
+ } else {
18866
+ helpStr = text;
18867
+ }
18868
+ if (helpStr) {
18869
+ context.write(`${helpStr}
18870
+ `);
18871
+ }
18872
+ });
18873
+ return this;
18874
+ }
18875
+ /**
18876
+ * Output help information if help flags specified
18877
+ *
18878
+ * @param {Array} args - array of options to search for help flags
18879
+ * @private
18880
+ */
18881
+ _outputHelpIfRequested(args) {
18882
+ const helpOption = this._getHelpOption();
18883
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
18884
+ if (helpRequested) {
18885
+ this.outputHelp();
18886
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
18887
+ }
18888
+ }
18889
+ };
18890
+ __name(_Command12, "Command");
18891
+ var Command13 = _Command12;
18892
+ function incrementNodeInspectorPort(args) {
18893
+ return args.map((arg) => {
18894
+ if (!arg.startsWith("--inspect")) {
18895
+ return arg;
18896
+ }
18897
+ let debugOption;
18898
+ let debugHost = "127.0.0.1";
18899
+ let debugPort = "9229";
18900
+ let match;
18901
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
18902
+ debugOption = match[1];
18903
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
18904
+ debugOption = match[1];
18905
+ if (/^\d+$/.test(match[3])) {
18906
+ debugPort = match[3];
18907
+ } else {
18908
+ debugHost = match[3];
18909
+ }
18910
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
18911
+ debugOption = match[1];
18912
+ debugHost = match[3];
18913
+ debugPort = match[4];
18914
+ }
18915
+ if (debugOption && debugPort !== "0") {
18916
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
18917
+ }
18918
+ return arg;
18919
+ });
18920
+ }
18921
+ __name(incrementNodeInspectorPort, "incrementNodeInspectorPort");
18922
+ function useColor() {
18923
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
18924
+ return false;
18925
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
18926
+ return true;
18927
+ return void 0;
18928
+ }
18929
+ __name(useColor, "useColor");
18930
+ exports.Command = Command13;
18931
+ exports.useColor = useColor;
18932
+ }
18933
+ });
18934
+
18935
+ // node_modules/commander/index.js
18936
+ var require_commander = __commonJS({
18937
+ "node_modules/commander/index.js"(exports) {
18938
+ "use strict";
18939
+ init_esm_shims();
18940
+ var { Argument: Argument2 } = require_argument();
18941
+ var { Command: Command13 } = require_command();
18942
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
18943
+ var { Help: Help2 } = require_help();
18944
+ var { Option: Option2 } = require_option();
18945
+ exports.program = new Command13();
18946
+ exports.createCommand = (name) => new Command13(name);
18947
+ exports.createOption = (flags, description) => new Option2(flags, description);
18948
+ exports.createArgument = (name, description) => new Argument2(name, description);
18949
+ exports.Command = Command13;
18950
+ exports.Option = Option2;
18951
+ exports.Argument = Argument2;
18952
+ exports.Help = Help2;
18953
+ exports.CommanderError = CommanderError2;
18954
+ exports.InvalidArgumentError = InvalidArgumentError2;
18955
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
18956
+ }
18957
+ });
18958
+
18959
+ // node_modules/commander/esm.mjs
18960
+ var import_index, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
18961
+ var init_esm = __esm({
18962
+ "node_modules/commander/esm.mjs"() {
18963
+ "use strict";
18964
+ init_esm_shims();
18965
+ import_index = __toESM(require_commander(), 1);
18966
+ ({
18967
+ program,
18968
+ createCommand,
18969
+ createArgument,
18970
+ createOption,
18971
+ CommanderError,
18972
+ InvalidArgumentError,
18973
+ InvalidOptionArgumentError,
18974
+ Command: (
18975
+ // deprecated old name
18976
+ Command
18977
+ ),
18978
+ Argument,
18979
+ Option,
18980
+ Help
18981
+ } = import_index.default);
18982
+ }
18983
+ });
18984
+
18985
+ // src/commands/load-plugin-bags.ts
18986
+ var load_plugin_bags_exports = {};
18987
+ __export(load_plugin_bags_exports, {
18988
+ Command: () => Command2,
18989
+ info: () => info
18990
+ });
18991
+ import { resolve as resolve5 } from "node:path";
18992
+ async function loadPluginBags($tw2, store, engine) {
18993
+ function makePluginBagName2(type, publisher, name) {
18994
+ return "$:/" + type + "/" + (publisher ? publisher + "/" : "") + name;
18995
+ }
18996
+ __name(makePluginBagName2, "makePluginBagName");
18997
+ function savePlugin(pluginFields, type, publisher, name) {
18998
+ const bagName = makePluginBagName2(type, publisher, name);
18999
+ const description = pluginFields.description ?? "(no description)";
19000
+ const is_plugin = true;
19001
+ return [
19002
+ store.upsertBag_PrismaPromise(bagName, description, is_plugin, { allowPrivilegedCharacters: true }),
19003
+ ...store.saveBagTiddlerFields_PrismaArray(pluginFields, bagName, null)
19004
+ // ...Object.values(tiddlers).flatMap((fields) => store.saveBagTiddlerFields_PrismaArray(fields, bagName, null))
19005
+ ].filter(truthy);
19006
+ }
19007
+ __name(savePlugin, "savePlugin");
19008
+ function collectPlugins(folder, type, publisher) {
19009
+ var pluginFolders = $tw2.utils.getSubdirectories(folder) || [];
19010
+ const prismaPromiseArray2 = [];
19011
+ for (var p = 0; p < pluginFolders.length; p++) {
19012
+ const pluginFolderName = pluginFolders[p];
19013
+ if ($tw2.boot.excludeRegExp.test(pluginFolderName)) continue;
19014
+ const pluginFields = $tw2.loadPluginFolder(resolve5(folder, pluginFolderName));
19015
+ if (!pluginFields?.title) continue;
19016
+ prismaPromiseArray2.push(...savePlugin(pluginFields, type, publisher, pluginFolderName));
19017
+ }
19018
+ prismaPromiseArray2.forEach((e) => {
19019
+ if (e[Symbol.toStringTag] !== "PrismaPromise") console.log(e);
19020
+ });
19021
+ return prismaPromiseArray2;
19022
+ }
19023
+ __name(collectPlugins, "collectPlugins");
19024
+ function collectPublisherPlugins(folder, type) {
19025
+ var publisherFolders = $tw2.utils.getSubdirectories(folder) || [];
19026
+ return publisherFolders.flatMap((publisherFolderName) => {
19027
+ if ($tw2.boot.excludeRegExp.test(publisherFolderName)) return [];
19028
+ return collectPlugins(resolve5(folder, publisherFolderName), type, publisherFolderName);
19029
+ });
19030
+ }
19031
+ __name(collectPublisherPlugins, "collectPublisherPlugins");
19032
+ ;
19033
+ const plugins = $tw2.getLibraryItemSearchPaths($tw2.config.pluginsPath, $tw2.config.pluginsEnvVar);
19034
+ const themes = $tw2.getLibraryItemSearchPaths($tw2.config.themesPath, $tw2.config.themesEnvVar);
19035
+ const languages = $tw2.getLibraryItemSearchPaths($tw2.config.languagesPath, $tw2.config.languagesEnvVar);
19036
+ const prismaPromiseArray = [
19037
+ ...plugins.flatMap((folder) => collectPublisherPlugins(folder, "plugins")),
19038
+ ...themes.flatMap((folder) => collectPublisherPlugins(folder, "themes")),
19039
+ ...languages.flatMap((folder) => collectPlugins(folder, "languages"))
19040
+ ];
19041
+ prismaPromiseArray.forEach((e) => {
19042
+ if (e[Symbol.toStringTag] !== "PrismaPromise") {
19043
+ if (Array.isArray(e)) console.log(e.length);
19044
+ else console.log(e);
19045
+ }
19046
+ });
19047
+ await engine.$transaction(prismaPromiseArray);
19048
+ }
19049
+ var info, _Command, Command2;
19050
+ var init_load_plugin_bags = __esm({
19051
+ "src/commands/load-plugin-bags.ts"() {
19052
+ "use strict";
19053
+ init_esm_shims();
19054
+ init_TiddlerStore();
19055
+ init_utils2();
19056
+ info = {
19057
+ name: "load-plugin-bags",
19058
+ description: "Load plugin bags from the TiddlyWiki5 plugins folder",
19059
+ arguments: [
19060
+ ["path", "Path to the TiddlyWiki5 plugins folder"]
19061
+ ],
19062
+ synchronous: true
19063
+ };
19064
+ _Command = class _Command {
19065
+ constructor(params, commander2, callback) {
19066
+ this.params = params;
19067
+ this.commander = commander2;
19068
+ this.callback = callback;
19069
+ }
19070
+ get $tw() {
19071
+ return this.commander.$tw;
19072
+ }
19073
+ async execute() {
19074
+ console.time(`${info.name} complete`);
19075
+ await loadPluginBags(
19076
+ this.$tw,
19077
+ TiddlerStore.fromCommander(this.commander, this.commander.engine),
19078
+ this.commander.engine
19079
+ );
19080
+ console.timeEnd(`${info.name} complete`);
19081
+ }
19082
+ };
19083
+ __name(_Command, "Command");
19084
+ Command2 = _Command;
19085
+ __name(loadPluginBags, "loadPluginBags");
19086
+ }
19087
+ });
19088
+
19089
+ // src/commands/render-tiddlywiki5.ts
19090
+ var render_tiddlywiki5_exports = {};
19091
+ __export(render_tiddlywiki5_exports, {
19092
+ Command: () => Command3,
19093
+ info: () => info2
19094
+ });
19095
+ import { resolve as resolve6 } from "node:path";
19096
+ var writeFileSync3, info2, _Command2, Command3;
19097
+ var init_render_tiddlywiki5 = __esm({
19098
+ "src/commands/render-tiddlywiki5.ts"() {
19099
+ "use strict";
19100
+ init_esm_shims();
19101
+ ({ writeFileSync: writeFileSync3 } = __require("fs"));
19102
+ info2 = {
19103
+ name: "render-tiddlywiki5",
19104
+ description: "Render the TiddlyWiki5 HTML file",
19105
+ arguments: [],
19106
+ synchronous: true
19107
+ };
19108
+ _Command2 = class _Command2 {
19109
+ constructor(params, commander2, callback) {
19110
+ this.params = params;
19111
+ this.commander = commander2;
19112
+ this.callback = callback;
19113
+ }
19114
+ async execute() {
19115
+ const result = this.commander.$tw.wiki.renderTiddler("text/plain", "$:/core/templates/tiddlywiki5.html", {
19116
+ variables: {
19117
+ saveTiddlerFilter: `
19118
+ $:/boot/boot.css
19119
+ $:/boot/boot.js
19120
+ $:/boot/bootprefix.js
19121
+ $:/core
19122
+ $:/library/sjcl.js
19123
+ $:/plugins/tiddlywiki/tiddlyweb
19124
+ $:/plugins/tiddlywiki/multiwikiclient
19125
+ $:/themes/tiddlywiki/snowwhite
19126
+ $:/themes/tiddlywiki/vanilla
19127
+ `
19128
+ }
19129
+ });
19130
+ const filepath = resolve6(this.commander.wikiPath, "tiddlywiki5.html");
19131
+ writeFileSync3(filepath, result);
19132
+ }
19133
+ };
19134
+ __name(_Command2, "Command");
19135
+ Command3 = _Command2;
19136
+ }
19137
+ });
19138
+
19139
+ // src/commands/load-wiki-folder.ts
19140
+ var load_wiki_folder_exports = {};
19141
+ __export(load_wiki_folder_exports, {
19142
+ Command: () => Command4,
19143
+ info: () => info3
19144
+ });
19145
+ import { resolve as resolve7 } from "path";
19146
+ function makePluginBagName(type, publisher, name) {
19147
+ return "$:/" + type + "/" + (publisher ? publisher + "/" : "") + name;
19148
+ }
19149
+ function loadWikiFolder({ $tw: $tw2, store, ...options }) {
19150
+ const path5 = __require("path"), fs3 = __require("fs");
19151
+ const wikiInfoPath = path5.resolve(options.wikiPath, $tw2.config.wikiInfo);
19152
+ let wikiInfo;
19153
+ if (fs3.existsSync(wikiInfoPath)) {
19154
+ wikiInfo = $tw2.utils.parseJSONSafe(fs3.readFileSync(wikiInfoPath, "utf8"), function() {
19155
+ return null;
19156
+ });
19157
+ }
19158
+ if (!wikiInfo) return [];
19159
+ const recipeList = [];
19160
+ const processPlugins = /* @__PURE__ */ __name(function(type, plugins) {
19161
+ $tw2.utils.each(plugins, function(pluginName) {
19162
+ const parts = pluginName.split("/");
19163
+ let publisher, name;
19164
+ if (parts.length === 2) {
19165
+ publisher = parts[0];
19166
+ name = parts[1];
19167
+ } else {
19168
+ name = parts[0];
19169
+ }
19170
+ recipeList.push({ bag_name: makePluginBagName(type, publisher, name), with_acl: false });
19171
+ });
19172
+ }, "processPlugins");
19173
+ processPlugins("plugins", wikiInfo.plugins);
19174
+ processPlugins("themes", wikiInfo.themes);
19175
+ processPlugins("languages", wikiInfo.languages);
19176
+ recipeList.push({
19177
+ bag_name: options.bagName,
19178
+ with_acl: true
19179
+ });
19180
+ recipeList.reverse();
19181
+ const tiddler_files_path = path5.resolve(options.wikiPath, $tw2.config.wikiTiddlersSubDir);
19182
+ const tiddlersFromPath = $tw2.loadTiddlersFromPath(
19183
+ resolve7($tw2.boot.corePath, $tw2.config.editionsPath, tiddler_files_path)
19184
+ );
19185
+ const is_plugin = false;
19186
+ return [
19187
+ // create the bag
19188
+ store.upsertBag_PrismaPromise(options.bagName, options.bagDescription, is_plugin),
19189
+ // create the recipe and recipe_bags entries
19190
+ ...store.upsertRecipe_PrismaArray(
19191
+ options.recipeName,
19192
+ options.recipeDescription,
19193
+ recipeList
19194
+ ),
19195
+ // save the tiddlers (this will skip attachments)
19196
+ ...store.saveTiddlersFromPath_PrismaArray(tiddlersFromPath, options.bagName)
19197
+ ];
19198
+ }
19199
+ var info3, _Command3, Command4;
19200
+ var init_load_wiki_folder = __esm({
19201
+ "src/commands/load-wiki-folder.ts"() {
19202
+ "use strict";
19203
+ init_esm_shims();
19204
+ init_TiddlerStore();
19205
+ info3 = {
19206
+ name: "load-wiki-folder",
19207
+ description: "Load a TiddlyWiki folder into a bag",
19208
+ arguments: [
19209
+ ["path", "Path to the TiddlyWiki5 plugins folder"],
19210
+ ["bag-name", "Name of the bag to load tiddlers into"],
19211
+ ["bag-description", "Description of the bag"],
19212
+ ["recipe-name", "Name of the recipe to create"],
19213
+ ["recipe-description", "Description of the recipe"]
19214
+ ],
19215
+ synchronous: true
19216
+ };
19217
+ _Command3 = class _Command3 {
19218
+ constructor(params, commander2, callback) {
19219
+ this.params = params;
19220
+ this.commander = commander2;
19221
+ this.callback = callback;
19222
+ }
19223
+ async execute() {
15782
19224
  if (this.params.length < 5) {
15783
19225
  return "Missing parameters for --mws-load-wiki-folder command";
15784
19226
  }
@@ -15788,7 +19230,7 @@ var init_mws_load_wiki_folder = __esm({
15788
19230
  bagDescription: this.params[2],
15789
19231
  recipeName: this.params[3],
15790
19232
  recipeDescription: this.params[4],
15791
- store: new TiddlerStore(this.commander, this.commander.engine),
19233
+ store: TiddlerStore.fromCommander(this.commander, this.commander.engine),
15792
19234
  $tw: this.commander.$tw
15793
19235
  }));
15794
19236
  console.log(info3.name, "complete:", this.params[0]);
@@ -15796,36 +19238,40 @@ var init_mws_load_wiki_folder = __esm({
15796
19238
  }
15797
19239
  };
15798
19240
  __name(_Command3, "Command");
15799
- Command3 = _Command3;
19241
+ Command4 = _Command3;
15800
19242
  __name(makePluginBagName, "makePluginBagName");
15801
19243
  __name(loadWikiFolder, "loadWikiFolder");
15802
19244
  }
15803
19245
  });
15804
19246
 
15805
- // src/commands/mws-save-archive.ts
15806
- var mws_save_archive_exports = {};
15807
- __export(mws_save_archive_exports, {
15808
- Command: () => Command4,
19247
+ // src/commands/save-archive.ts
19248
+ var save_archive_exports = {};
19249
+ __export(save_archive_exports, {
19250
+ Command: () => Command5,
15809
19251
  info: () => info4
15810
19252
  });
15811
19253
  import { resolve as resolve8 } from "path";
15812
19254
  import * as _fsp from "fs/promises";
15813
- var fsp, info4, _Command4, Command4;
15814
- var init_mws_save_archive = __esm({
15815
- "src/commands/mws-save-archive.ts"() {
19255
+ var fsp, info4, _Command4, Command5;
19256
+ var init_save_archive = __esm({
19257
+ "src/commands/save-archive.ts"() {
15816
19258
  "use strict";
15817
19259
  init_esm_shims();
15818
19260
  init_TiddlerStore();
15819
19261
  init_utils2();
15820
19262
  fsp = createStrictAwaitProxy(_fsp);
15821
19263
  info4 = {
15822
- name: "mws-save-archive",
19264
+ name: "save-archive",
19265
+ description: "Save an archive of recipes, bags and tiddlers to a directory",
19266
+ arguments: [
19267
+ ["path", "Path to the directory to save the archive"]
19268
+ ],
15823
19269
  synchronous: true
15824
19270
  };
15825
19271
  _Command4 = class _Command4 {
15826
- constructor(params, commander, callback) {
19272
+ constructor(params, commander2, callback) {
15827
19273
  this.params = params;
15828
- this.commander = commander;
19274
+ this.commander = commander2;
15829
19275
  this.callback = callback;
15830
19276
  }
15831
19277
  get $tw() {
@@ -15837,7 +19283,7 @@ var init_mws_save_archive = __esm({
15837
19283
  async execute() {
15838
19284
  if (this.params.length < 1) throw "Missing pathname";
15839
19285
  await this.commander.$transaction(async (prisma) => {
15840
- this.store = new TiddlerStore(this.commander, prisma);
19286
+ this.store = TiddlerStore.fromCommander(this.commander, prisma);
15841
19287
  await this.saveArchive();
15842
19288
  this.store = void 0;
15843
19289
  });
@@ -15904,35 +19350,39 @@ var init_mws_save_archive = __esm({
15904
19350
  }
15905
19351
  };
15906
19352
  __name(_Command4, "Command");
15907
- Command4 = _Command4;
19353
+ Command5 = _Command4;
15908
19354
  }
15909
19355
  });
15910
19356
 
15911
- // src/commands/mws-load-archive.ts
15912
- var mws_load_archive_exports = {};
15913
- __export(mws_load_archive_exports, {
15914
- Command: () => Command5,
19357
+ // src/commands/load-archive.ts
19358
+ var load_archive_exports = {};
19359
+ __export(load_archive_exports, {
19360
+ Command: () => Command6,
15915
19361
  info: () => info5
15916
19362
  });
15917
19363
  import { join as join2, resolve as resolve9 } from "path";
15918
19364
  import * as _fsp2 from "fs/promises";
15919
19365
  import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
15920
19366
  import { existsSync as existsSync3 } from "fs";
15921
- var fsp2, info5, _Command5, Command5, _Archiver, Archiver, _Archiver1, Archiver1, _Archiver2, Archiver2;
15922
- var init_mws_load_archive = __esm({
15923
- "src/commands/mws-load-archive.ts"() {
19367
+ var fsp2, info5, _Command5, Command6, _Archiver, Archiver, _Archiver1, Archiver1, _Archiver2, Archiver2;
19368
+ var init_load_archive = __esm({
19369
+ "src/commands/load-archive.ts"() {
15924
19370
  "use strict";
15925
19371
  init_esm_shims();
15926
19372
  init_utils2();
15927
19373
  fsp2 = createStrictAwaitProxy(_fsp2);
15928
19374
  info5 = {
15929
- name: "mws-load-archive",
19375
+ name: "load-archive",
19376
+ description: "Load a MWS archive into the database",
19377
+ arguments: [
19378
+ ["archivePath", "Path to the archive to load"]
19379
+ ],
15930
19380
  synchronous: true
15931
19381
  };
15932
19382
  _Command5 = class _Command5 {
15933
- constructor(params, commander, callback) {
19383
+ constructor(params, commander2, callback) {
15934
19384
  this.params = params;
15935
- this.commander = commander;
19385
+ this.commander = commander2;
15936
19386
  this.callback = callback;
15937
19387
  }
15938
19388
  async execute() {
@@ -15953,10 +19403,10 @@ var init_mws_load_archive = __esm({
15953
19403
  }
15954
19404
  };
15955
19405
  __name(_Command5, "Command");
15956
- Command5 = _Command5;
19406
+ Command6 = _Command5;
15957
19407
  _Archiver = class _Archiver {
15958
- constructor(commander) {
15959
- this.commander = commander;
19408
+ constructor(commander2) {
19409
+ this.commander = commander2;
15960
19410
  }
15961
19411
  };
15962
19412
  __name(_Archiver, "Archiver");
@@ -16153,27 +19603,29 @@ var init_mws_load_archive = __esm({
16153
19603
  }
16154
19604
  });
16155
19605
 
16156
- // src/commands/mws-init-store.ts
16157
- var mws_init_store_exports = {};
16158
- __export(mws_init_store_exports, {
16159
- Command: () => Command6,
19606
+ // src/commands/init-store.ts
19607
+ var init_store_exports = {};
19608
+ __export(init_store_exports, {
19609
+ Command: () => Command7,
16160
19610
  info: () => info6
16161
19611
  });
16162
19612
  import { resolve as resolve10 } from "node:path";
16163
- var info6, _Command6, Command6;
16164
- var init_mws_init_store = __esm({
16165
- "src/commands/mws-init-store.ts"() {
19613
+ var info6, _Command6, Command7;
19614
+ var init_init_store = __esm({
19615
+ "src/commands/init-store.ts"() {
16166
19616
  "use strict";
16167
19617
  init_esm_shims();
16168
19618
  init_utils2();
16169
19619
  info6 = {
16170
- name: "mws-init-store",
19620
+ name: "init-store",
19621
+ description: "Initialize the MWS Store",
19622
+ arguments: [],
16171
19623
  synchronous: true
16172
19624
  };
16173
19625
  _Command6 = class _Command6 {
16174
- constructor(params, commander, callback) {
19626
+ constructor(params, commander2, callback) {
16175
19627
  this.params = params;
16176
- this.commander = commander;
19628
+ this.commander = commander2;
16177
19629
  this.callback = callback;
16178
19630
  }
16179
19631
  get $tw() {
@@ -16203,26 +19655,26 @@ var init_mws_init_store = __esm({
16203
19655
  });
16204
19656
  const tweditions = resolve10(dist_require_resolve("tiddlywiki"), "../../editions");
16205
19657
  this.commander.addCommandTokens([
16206
- "--mws-load-plugin-bags",
16207
- "--mws-load-wiki-folder",
19658
+ "--load-plugin-bags",
19659
+ "--load-wiki-folder",
16208
19660
  dist_resolve("../editions/mws-docs"),
16209
19661
  "mws-docs",
16210
19662
  "MWS Documentation from https://mws.tiddlywiki.com",
16211
19663
  "mws-docs",
16212
19664
  "MWS Documentation from https://mws.tiddlywiki.com",
16213
- "--mws-load-wiki-folder",
19665
+ "--load-wiki-folder",
16214
19666
  resolve10(tweditions, "tw5.com"),
16215
19667
  "docs",
16216
19668
  "TiddlyWiki Documentation from https://tiddlywiki.com",
16217
19669
  "docs",
16218
19670
  "TiddlyWiki Documentation from https://tiddlywiki.com",
16219
- "--mws-load-wiki-folder",
19671
+ "--load-wiki-folder",
16220
19672
  resolve10(tweditions, "dev"),
16221
19673
  "dev",
16222
19674
  "TiddlyWiki Developer Documentation from https://tiddlywiki.com/dev",
16223
19675
  "dev-docs",
16224
19676
  "TiddlyWiki Developer Documentation from https://tiddlywiki.com/dev",
16225
- "--mws-load-wiki-folder",
19677
+ "--load-wiki-folder",
16226
19678
  resolve10(tweditions, "tour"),
16227
19679
  "tour",
16228
19680
  "TiddlyWiki Interactive Tour from https://tiddlywiki.com",
@@ -16234,14 +19686,14 @@ var init_mws_init_store = __esm({
16234
19686
  }
16235
19687
  };
16236
19688
  __name(_Command6, "Command");
16237
- Command6 = _Command6;
19689
+ Command7 = _Command6;
16238
19690
  }
16239
19691
  });
16240
19692
 
16241
- // src/commands/mws-listen.ts
16242
- var mws_listen_exports = {};
16243
- __export(mws_listen_exports, {
16244
- Command: () => Command7,
19693
+ // src/commands/listen.ts
19694
+ var listen_exports = {};
19695
+ __export(listen_exports, {
19696
+ Command: () => Command8,
16245
19697
  ListenerBase: () => ListenerBase,
16246
19698
  ListenerHTTP: () => ListenerHTTP,
16247
19699
  ListenerHTTPS: () => ListenerHTTPS,
@@ -16251,12 +19703,18 @@ import { ok as ok6 } from "assert";
16251
19703
  import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
16252
19704
  import { createServer } from "http";
16253
19705
  import * as http2 from "node:http2";
16254
- var _ListenerBase, ListenerBase, _ListenerHTTPS, ListenerHTTPS, _ListenerHTTP, ListenerHTTP, info7, _Command7, Command7;
16255
- var init_mws_listen = __esm({
16256
- "src/commands/mws-listen.ts"() {
19706
+ var info7, _ListenerBase, ListenerBase, _ListenerHTTPS, ListenerHTTPS, _ListenerHTTP, ListenerHTTP, _Command7, Command8;
19707
+ var init_listen = __esm({
19708
+ "src/commands/listen.ts"() {
16257
19709
  "use strict";
16258
19710
  init_esm_shims();
16259
19711
  init_router();
19712
+ info7 = {
19713
+ name: "listen",
19714
+ description: "Start the server and listen for incoming requests",
19715
+ arguments: [],
19716
+ synchronous: true
19717
+ };
16260
19718
  _ListenerBase = class _ListenerBase {
16261
19719
  constructor(server3, router, bindInfo) {
16262
19720
  this.server = server3;
@@ -16320,18 +19778,14 @@ var init_mws_listen = __esm({
16320
19778
  };
16321
19779
  __name(_ListenerHTTP, "ListenerHTTP");
16322
19780
  ListenerHTTP = _ListenerHTTP;
16323
- info7 = {
16324
- name: "mws-listen",
16325
- synchronous: true
16326
- };
16327
19781
  _Command7 = class _Command7 {
16328
- constructor(params, commander, listenConfig, onListenersCreated) {
19782
+ constructor(params, commander2, listenConfig, onListenersCreated) {
16329
19783
  this.params = params;
16330
- this.commander = commander;
19784
+ this.commander = commander2;
16331
19785
  if (this.params.length) throw `${info7.name}: No parameters allowed. Please put listener options in the config file.`;
16332
19786
  this.execute = async () => {
16333
19787
  this.commander.addCommandTokens([
16334
- "--mws-render-tiddlywiki5",
19788
+ "--render-tiddlywiki5",
16335
19789
  "--divider"
16336
19790
  ]);
16337
19791
  const router = await Router2.makeRouter(
@@ -16356,58 +19810,64 @@ var init_mws_listen = __esm({
16356
19810
  }
16357
19811
  };
16358
19812
  __name(_Command7, "Command");
16359
- Command7 = _Command7;
19813
+ Command8 = _Command7;
16360
19814
  }
16361
19815
  });
16362
19816
 
16363
19817
  // src/commands/divider.ts
16364
19818
  var divider_exports = {};
16365
19819
  __export(divider_exports, {
16366
- Command: () => Command8,
19820
+ Command: () => Command9,
16367
19821
  info: () => info8
16368
19822
  });
16369
- var info8, _Command8, Command8;
19823
+ var info8, _Command8, Command9;
16370
19824
  var init_divider = __esm({
16371
19825
  "src/commands/divider.ts"() {
16372
19826
  "use strict";
16373
19827
  init_esm_shims();
16374
19828
  info8 = {
16375
19829
  name: "divider",
16376
- synchronous: true
19830
+ description: "A no-op command to delimit param concatenation.",
19831
+ arguments: [],
19832
+ synchronous: true,
19833
+ internal: true
16377
19834
  };
16378
19835
  _Command8 = class _Command8 {
16379
- constructor(params, commander) {
19836
+ constructor(params, commander2) {
16380
19837
  this.params = params;
16381
- this.commander = commander;
19838
+ this.commander = commander2;
16382
19839
  if (this.params.length) throw `${info8.name}: No parameters allowed. This is a no-op command.`;
16383
19840
  }
16384
19841
  execute() {
16385
19842
  }
16386
19843
  };
16387
19844
  __name(_Command8, "Command");
16388
- Command8 = _Command8;
19845
+ Command9 = _Command8;
16389
19846
  }
16390
19847
  });
16391
19848
 
16392
19849
  // src/commands/tests-complete.ts
16393
19850
  var tests_complete_exports = {};
16394
19851
  __export(tests_complete_exports, {
16395
- Command: () => Command9,
19852
+ Command: () => Command10,
16396
19853
  info: () => info9
16397
19854
  });
16398
- var info9, _Command9, Command9;
19855
+ var info9, _Command9, Command10;
16399
19856
  var init_tests_complete = __esm({
16400
19857
  "src/commands/tests-complete.ts"() {
16401
19858
  "use strict";
16402
19859
  init_esm_shims();
16403
19860
  info9 = {
16404
19861
  name: "tests-complete",
16405
- synchronous: true
19862
+ description: "Tests completed successfully.",
19863
+ arguments: [],
19864
+ synchronous: true,
19865
+ internal: true
16406
19866
  };
16407
19867
  _Command9 = class _Command9 {
16408
- constructor(params, commander) {
19868
+ constructor(params, commander2) {
16409
19869
  this.params = params;
16410
- this.commander = commander;
19870
+ this.commander = commander2;
16411
19871
  }
16412
19872
  execute() {
16413
19873
  console.log("Tests completed successfully.");
@@ -16415,30 +19875,33 @@ var init_tests_complete = __esm({
16415
19875
  }
16416
19876
  };
16417
19877
  __name(_Command9, "Command");
16418
- Command9 = _Command9;
19878
+ Command10 = _Command9;
16419
19879
  }
16420
19880
  });
16421
19881
 
16422
- // src/commands/mws-client-build.ts
16423
- var mws_client_build_exports = {};
16424
- __export(mws_client_build_exports, {
16425
- Command: () => Command10,
19882
+ // src/commands/client-build.ts
19883
+ var client_build_exports = {};
19884
+ __export(client_build_exports, {
19885
+ Command: () => Command11,
16426
19886
  info: () => info10
16427
19887
  });
16428
- var info10, _Command10, Command10;
16429
- var init_mws_client_build = __esm({
16430
- "src/commands/mws-client-build.ts"() {
19888
+ var info10, _Command10, Command11;
19889
+ var init_client_build = __esm({
19890
+ "src/commands/client-build.ts"() {
16431
19891
  "use strict";
16432
19892
  init_esm_shims();
16433
19893
  init_setupDevServer();
16434
19894
  info10 = {
16435
- name: "mws-client-build",
16436
- synchronous: true
19895
+ name: "client-build",
19896
+ description: "Build the client for the TiddlyWiki5 server",
19897
+ arguments: [],
19898
+ synchronous: true,
19899
+ internal: true
16437
19900
  };
16438
19901
  _Command10 = class _Command10 {
16439
- constructor(params, commander) {
19902
+ constructor(params, commander2) {
16440
19903
  this.params = params;
16441
- this.commander = commander;
19904
+ this.commander = commander2;
16442
19905
  if (this.params.length) throw `${info10.name}: No parameters allowed. This is a no-op command.`;
16443
19906
  }
16444
19907
  async execute() {
@@ -16448,7 +19911,37 @@ var init_mws_client_build = __esm({
16448
19911
  }
16449
19912
  };
16450
19913
  __name(_Command10, "Command");
16451
- Command10 = _Command10;
19914
+ Command11 = _Command10;
19915
+ }
19916
+ });
19917
+
19918
+ // src/commands/help.ts
19919
+ var help_exports = {};
19920
+ __export(help_exports, {
19921
+ Command: () => Command12,
19922
+ info: () => info11
19923
+ });
19924
+ var info11, _Command11, Command12;
19925
+ var init_help = __esm({
19926
+ "src/commands/help.ts"() {
19927
+ "use strict";
19928
+ init_esm_shims();
19929
+ info11 = {
19930
+ name: "help",
19931
+ description: "Print this help message",
19932
+ arguments: [],
19933
+ synchronous: true
19934
+ };
19935
+ _Command11 = class _Command11 {
19936
+ constructor(params, commander2) {
19937
+ this.params = params;
19938
+ this.commander = commander2;
19939
+ }
19940
+ async execute() {
19941
+ }
19942
+ };
19943
+ __name(_Command11, "Command");
19944
+ Command12 = _Command11;
16452
19945
  }
16453
19946
  });
16454
19947
 
@@ -16458,27 +19951,29 @@ var init_commands = __esm({
16458
19951
  "src/commands/index.ts"() {
16459
19952
  "use strict";
16460
19953
  init_esm_shims();
16461
- init_mws_load_plugin_bags();
16462
- init_mws_render_tiddlywiki5();
16463
- init_mws_load_wiki_folder();
16464
- init_mws_save_archive();
16465
- init_mws_load_archive();
16466
- init_mws_init_store();
16467
- init_mws_listen();
19954
+ init_load_plugin_bags();
19955
+ init_render_tiddlywiki5();
19956
+ init_load_wiki_folder();
19957
+ init_save_archive();
19958
+ init_load_archive();
19959
+ init_init_store();
19960
+ init_listen();
16468
19961
  init_divider();
16469
19962
  init_tests_complete();
16470
- init_mws_client_build();
19963
+ init_client_build();
19964
+ init_help();
16471
19965
  commands = {
16472
- [info.name]: mws_load_plugin_bags_exports,
16473
- [info2.name]: mws_render_tiddlywiki5_exports,
16474
- [info3.name]: mws_load_wiki_folder_exports,
16475
- [info4.name]: mws_save_archive_exports,
16476
- [info5.name]: mws_load_archive_exports,
16477
- [info6.name]: mws_init_store_exports,
16478
- [info7.name]: mws_listen_exports,
19966
+ [info.name]: load_plugin_bags_exports,
19967
+ [info2.name]: render_tiddlywiki5_exports,
19968
+ [info3.name]: load_wiki_folder_exports,
19969
+ [info4.name]: save_archive_exports,
19970
+ [info5.name]: load_archive_exports,
19971
+ [info6.name]: init_store_exports,
19972
+ [info7.name]: listen_exports,
19973
+ [info11.name]: help_exports,
16479
19974
  [info8.name]: divider_exports,
16480
19975
  [info9.name]: tests_complete_exports,
16481
- [info10.name]: mws_client_build_exports
19976
+ [info10.name]: client_build_exports
16482
19977
  };
16483
19978
  }
16484
19979
  });
@@ -16567,7 +20062,7 @@ var init_sqlite_adapter = __esm({
16567
20062
  // src/commander.ts
16568
20063
  import * as path4 from "node:path";
16569
20064
  import { PrismaClient as PrismaClient2 } from "@prisma/client";
16570
- import { existsSync as existsSync6, mkdirSync as mkdirSync2 } from "node:fs";
20065
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "node:fs";
16571
20066
  import { ok as ok7 } from "node:assert";
16572
20067
  var _StartupCommander, StartupCommander, _Commander, Commander;
16573
20068
  var init_commander = __esm({
@@ -16576,6 +20071,8 @@ var init_commander = __esm({
16576
20071
  init_esm_shims();
16577
20072
  init_sessions();
16578
20073
  init_attachments();
20074
+ init_utils2();
20075
+ init_esm();
16579
20076
  init_commands();
16580
20077
  init_sqlite_adapter();
16581
20078
  _StartupCommander = class _StartupCommander {
@@ -16585,6 +20082,7 @@ var init_commander = __esm({
16585
20082
  this.PasswordService = PasswordService;
16586
20083
  /** Signals that database setup is required. May be set to false by any qualified setup command. */
16587
20084
  this.setupRequired = true;
20085
+ this.fieldModules = $tw2.Tiddler.fieldModules;
16588
20086
  if (config.config?.pathPrefix) {
16589
20087
  ok7(config.config.pathPrefix.startsWith("/"), "pathPrefix must start with a slash");
16590
20088
  ok7(!config.config.pathPrefix.endsWith("/"), "pathPrefix must not end with a slash");
@@ -16640,9 +20138,33 @@ var init_commander = __esm({
16640
20138
  config.listeners = [];
16641
20139
  config.onListenersCreated = void 0;
16642
20140
  this.create_mws_listen = (params) => {
16643
- return new mws_listen_exports.Command(params, this, listeners, onListenersCreated);
20141
+ return new listen_exports.Command(params, this, listeners, onListenersCreated);
16644
20142
  };
16645
20143
  }
20144
+ async init() {
20145
+ await super.init();
20146
+ this.program = new Command();
20147
+ const pkg = JSON.parse(readFileSync4(dist_resolve("../package.json"), "utf-8"));
20148
+ this.program.name("mws").description(pkg.description).version(pkg.version).enablePositionalOptions().passThroughOptions().showHelpAfterError();
20149
+ Object.keys(commands).forEach((key) => {
20150
+ const c = commands[key];
20151
+ if (c.info.internal) return;
20152
+ if (c.info.name === "help") return;
20153
+ const command = this.program.command(c.info.name);
20154
+ command.description(c.info.description);
20155
+ c.info.arguments.forEach(([name, description]) => {
20156
+ command.argument(name, description);
20157
+ });
20158
+ c.info.options?.forEach(([name, description]) => {
20159
+ command.option(name, description);
20160
+ });
20161
+ command.action((...args) => {
20162
+ const command2 = args.pop();
20163
+ const options = args.pop();
20164
+ this.addCommandTokens(["--" + command2.name(), ...args]);
20165
+ });
20166
+ });
20167
+ }
16646
20168
  static initCommands(moduleType) {
16647
20169
  if (moduleType) throw new Error("moduleType is not implemented");
16648
20170
  }
@@ -16658,15 +20180,34 @@ var init_commander = __esm({
16658
20180
  */
16659
20181
  execute(commandTokens) {
16660
20182
  console.log("Commander", commandTokens);
20183
+ this.setPromise();
20184
+ this.commandTokens = [];
20185
+ switch (commandTokens[0]) {
20186
+ // internal dev commands
20187
+ case "--client-build":
20188
+ this.commandTokens.push(...commandTokens);
20189
+ break;
20190
+ default:
20191
+ this.program.parse(commandTokens, { from: "user" });
20192
+ break;
20193
+ }
20194
+ this.executeNextCommand();
20195
+ return this.promise;
20196
+ }
20197
+ executeInternal(commandTokens) {
20198
+ console.log("Commander", commandTokens);
20199
+ this.setPromise();
16661
20200
  this.commandTokens = commandTokens;
20201
+ this.executeNextCommand();
20202
+ return this.promise;
20203
+ }
20204
+ setPromise() {
16662
20205
  this.promise = new Promise((resolve13, reject) => {
16663
20206
  this.callback = (err) => {
16664
20207
  if (err) this.$tw.utils.error("Error: " + err);
16665
20208
  err ? reject(err) : resolve13();
16666
20209
  };
16667
20210
  });
16668
- this.executeNextCommand();
16669
- return this.promise;
16670
20211
  }
16671
20212
  /*
16672
20213
  Execute the next command in the sequence
@@ -16693,17 +20234,16 @@ var init_commander = __esm({
16693
20234
  this.nextToken = nextCommand === -1 ? this.commandTokens.length : nextCommand;
16694
20235
  if (commandName !== divider_exports.info.name)
16695
20236
  console.log("Commander executing", commandName, params);
16696
- const paramsIfMandetory = !command.info.mandatoryParameters ? params : this.extractNamedParameters(params, command.info.mandatoryParameters);
16697
20237
  if (typeof params === "string") {
16698
20238
  this.callback(params);
16699
20239
  return;
16700
20240
  }
16701
20241
  new Promise(async (resolve13) => {
16702
- const { Command: Command11, info: info11 } = command;
20242
+ const { Command: Command13, info: info12 } = command;
16703
20243
  try {
16704
- c = info11.name === "mws-listen" ? this.create_mws_listen(paramsIfMandetory) : new Command11(paramsIfMandetory, this, info11.synchronous ? void 0 : resolve13);
20244
+ c = info12.name === listen_exports.info.name ? this.create_mws_listen(params) : new Command13(params, this, info12.synchronous ? void 0 : resolve13);
16705
20245
  err = await c.execute();
16706
- if (err || info11.synchronous) resolve13(err);
20246
+ if (err || info12.synchronous) resolve13(err);
16707
20247
  } catch (e) {
16708
20248
  resolve13(e);
16709
20249
  }
@@ -16849,21 +20389,22 @@ async function startServer(config) {
16849
20389
  const passwordMasterKey = readFileSync5(config.passwordMasterKeyFile, "utf8").trim();
16850
20390
  config.onPasswordKeyFileRead?.();
16851
20391
  config.wikiPath = resolve12(config.wikiPath);
16852
- const commander = new Commander(
20392
+ const commander2 = new Commander(
16853
20393
  config,
16854
20394
  await bootTiddlyWiki(config.wikiPath),
16855
20395
  await createPasswordService(passwordMasterKey)
16856
20396
  );
16857
- await commander.init();
20397
+ await commander2.init();
16858
20398
  const cli = process.argv.slice(2);
16859
- await commander.execute([
16860
- ...cli.length ? cli : [
16861
- "--mws-init-store",
16862
- "--mws-listen"
16863
- ]
16864
- ]);
16865
- if (commander.setupRequired) {
16866
- console.log("MWS setup required. Please run either --mws-init-store or --mws-load-archive");
20399
+ if (cli.length)
20400
+ await commander2.execute(cli);
20401
+ else
20402
+ await commander2.executeInternal([
20403
+ "--init-store",
20404
+ "--listen"
20405
+ ]);
20406
+ if (commander2.setupRequired) {
20407
+ console.log("MWS setup required. Please run either init-store or load-archive");
16867
20408
  process.exit(1);
16868
20409
  }
16869
20410
  }