@aventusjs/cli 0.0.39 → 0.0.40

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.
@@ -108,6 +108,8 @@ declare abstract class AventusTemplate {
108
108
  protected removeIndent(text: string): string;
109
109
  /** Exec a command. For example: "npm i" */
110
110
  protected exec(cmd: string, asAdmin?: boolean): Promise<void>;
111
+ /** Exec an aventus command */
112
+ protected aventusCommand(cmd: string, args?: any[]): Promise<void>;
111
113
  /** Show an error message inside the IDE */
112
114
  protected showErrorMessage(msg: string): void;
113
115
  /** Show a warning message inside the IDE */
@@ -1,5 +1,5 @@
1
1
  import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs'
2
- import { join, normalize, sep } from 'path'
2
+ import { dirname, join, normalize, sep } from 'path'
3
3
 
4
4
  export type Version = `${number}.${number}.${number}`
5
5
  export interface InputOptions {
@@ -24,6 +24,7 @@ export type WriteInfo = {
24
24
  rawContent: string,
25
25
  content: string,
26
26
  isDir: boolean
27
+ isBinary?: boolean
27
28
  }
28
29
  export type WriteCallback = (info: WriteInfo) => void | boolean;
29
30
 
@@ -130,9 +131,13 @@ export abstract class AventusTemplate {
130
131
  this.runCommand("error", e);
131
132
  }
132
133
  })
133
- this.run(destination).then(() => {
134
- process.exit();
135
- })
134
+ this.run(destination).then(
135
+ () => process.exit(),
136
+ (error) => {
137
+ console.error(error);
138
+ process.exit(1);
139
+ }
140
+ )
136
141
  })
137
142
  }
138
143
 
@@ -260,8 +265,9 @@ export abstract class AventusTemplate {
260
265
  AventusExtension.ConfigTemplate
261
266
  ]
262
267
  let filesPath: string[] = [];
263
- const _internalLoop = async (currentPath) => {
264
- try {
268
+ const directories: string[] = [];
269
+ const filesToWrite: { path: string, content: string | Buffer }[] = [];
270
+ const _internalLoop = async (currentPath: string) => {
265
271
  let files = readdirSync(currentPath);
266
272
  for (let file of files) {
267
273
  let templatePath = currentPath + sep + file;
@@ -282,22 +288,28 @@ export abstract class AventusTemplate {
282
288
  }
283
289
  const result = cb(writeInfo)
284
290
  if (result === false) continue;
285
- mkdirSync(exportPath, { recursive: true });
291
+ directories.push(exportPath);
286
292
  await _internalLoop(templatePath);
287
293
  }
288
294
  else {
289
295
  if (templatePath == this.templatePath + sep + AventusExtension.Template) {
290
296
  continue;
291
297
  }
292
- let rawCtx = readFileSync(templatePath, 'utf-8');
293
- this.variables["namespace"] = await this.runCommandWithAnswer("getNamespace", exportPath);
294
- let ctx = this.replaceVariables(rawCtx);
295
- ctx = this.replaceBlocks(ctx);
296
- ctx = this.replaceIfs(ctx);
298
+ const rawBytes = readFileSync(templatePath);
299
+ const rawCtx = rawBytes.toString('utf-8');
300
+ const isBinary = rawBytes.includes(0) || !Buffer.from(rawCtx, 'utf-8').equals(rawBytes);
301
+ let ctx = '';
302
+ if (!isBinary) {
303
+ this.variables["namespace"] = await this.runCommandWithAnswer("getNamespace", exportPath);
304
+ ctx = this.replaceVariables(rawCtx);
305
+ ctx = this.replaceBlocks(ctx);
306
+ ctx = this.replaceIfs(ctx);
307
+ }
297
308
  const writeInfo: WriteInfo = {
298
309
  content: ctx,
299
310
  isDir: false,
300
- rawContent: rawCtx,
311
+ rawContent: isBinary ? '' : rawCtx,
312
+ isBinary,
301
313
  templatePath: templatePath,
302
314
  writePath: exportPath,
303
315
  relativePath: relativePath
@@ -305,28 +317,32 @@ export abstract class AventusTemplate {
305
317
  const result = cb(writeInfo)
306
318
 
307
319
  if (result === false) continue;
320
+ let writePath = normalize(writeInfo.writePath);
308
321
  if (!configPattern.includes(file)) {
309
- writeFileSync(exportPath, writeInfo.content);
310
- if (exportPath.endsWith(".avt")) {
311
- filesPath.push(writeInfo.writePath);
322
+ filesToWrite.push({ path: writePath, content: isBinary ? rawBytes : writeInfo.content });
323
+ if (writePath.endsWith(".avt")) {
324
+ filesPath.push(writePath);
312
325
  }
313
326
  }
314
327
  else {
315
328
  if (file == AventusExtension.ConfigTemplate) {
316
- exportPath = exportPath.replace(AventusExtension.ConfigTemplate, AventusExtension.Config)
329
+ writePath = writePath.replace(AventusExtension.ConfigTemplate, AventusExtension.Config)
317
330
  }
318
- configFiles[exportPath] = writeInfo.content;
331
+ configFiles[writePath] = writeInfo.content;
319
332
  }
320
333
  }
321
334
  }
322
- } catch (e) {
323
- console.log(e);
324
- }
325
335
  }
326
336
 
327
337
  await _internalLoop(this.templatePath);
338
+ for (const directory of directories) mkdirSync(directory, { recursive: true });
339
+ for (const file of filesToWrite) {
340
+ mkdirSync(dirname(file.path), { recursive: true });
341
+ writeFileSync(file.path, file.content);
342
+ }
328
343
  // Force config to be written at the end
329
344
  for (let configPath in configFiles) {
345
+ mkdirSync(dirname(configPath), { recursive: true });
330
346
  writeFileSync(configPath, configFiles[configPath]);
331
347
  filesPath.push(configPath);
332
348
  }
@@ -341,7 +357,7 @@ export abstract class AventusTemplate {
341
357
  for (let varName in this.variables) {
342
358
  const regex = new RegExp('\\$\\{\\{' + varName + '\\}\\}', 'gm');
343
359
  const value = this.variables[varName] ?? ''
344
- ctx = ctx.replace(regex, value);
360
+ ctx = ctx.replace(regex, () => value);
345
361
  }
346
362
  return ctx;
347
363
  }
@@ -362,49 +378,42 @@ export abstract class AventusTemplate {
362
378
 
363
379
 
364
380
  protected replaceIfs(ctx: string) {
365
- for (let ifName in this.ifs) {
366
- const regex = new RegExp('#if\\{\\{' + ifName + '\\}\\}((\\s|\\S)*)#end\\{\\{' + ifName + '\\}\\}', 'gm');
367
- if (this.ifs[ifName]) {
368
- let m: RegExpExecArray | null;
369
- while ((m = regex.exec(ctx)) !== null) {
370
- if (m.index === regex.lastIndex) {
371
- regex.lastIndex++;
372
- }
373
- ctx = ctx.replace(m[0], m[1]);
374
- }
381
+ type Frame = { name?: string, start: number, cursor: number, parts: string[] };
382
+ const frames: Frame[] = [{ start: 0, cursor: 0, parts: [] }];
383
+ const marker = /#(if|end)\{\{([^{}]+)\}\}/g;
384
+ let match: RegExpExecArray | null;
385
+ while ((match = marker.exec(ctx)) !== null) {
386
+ const name = match[2];
387
+ if (!Object.prototype.hasOwnProperty.call(this.ifs, name)) continue;
388
+ const current = frames[frames.length - 1];
389
+ if (match[1] === 'if') {
390
+ current.parts.push(ctx.slice(current.cursor, match.index));
391
+ frames.push({ name, start: match.index, cursor: marker.lastIndex, parts: [] });
375
392
  }
376
- else {
377
- ctx = ctx.replace(regex, "");
393
+ else if (current.name === name) {
394
+ current.parts.push(ctx.slice(current.cursor, match.index));
395
+ frames.pop();
396
+ const parent = frames[frames.length - 1];
397
+ if (this.ifs[name]) parent.parts.push(current.parts.join(''));
398
+ parent.cursor = marker.lastIndex;
378
399
  }
379
400
  }
380
- return ctx;
401
+ while (frames.length > 1) {
402
+ const unfinished = frames.pop()!;
403
+ const parent = frames[frames.length - 1];
404
+ parent.parts.push(ctx.slice(unfinished.start));
405
+ parent.cursor = ctx.length;
406
+ }
407
+ const root = frames[0];
408
+ return root.parts.join('') + ctx.slice(root.cursor);
381
409
  }
382
410
  protected replaceBlocks(ctx: string) {
383
411
  for (let blockName in this.blocks) {
384
- const regex = new RegExp('#\\{\\{' + blockName + '\\}\\}((\\s|\\S)*)#\\{\\{' + blockName + '\\/\\}\\}', 'gm');
412
+ const regex = new RegExp('#\\{\\{' + blockName + '\\}\\}((\\s|\\S)*?)#\\{\\{' + blockName + '\\/\\}\\}', 'gm');
385
413
  const block = this.blocks[blockName];
386
414
  const contentBefore = block.before();
387
415
  const contentAfter = block.after();
388
-
389
- let m: RegExpExecArray | null;
390
- while ((m = regex.exec(ctx)) !== null) {
391
- // This is necessary to avoid infinite loops with zero-width matches
392
- if (m.index === regex.lastIndex) {
393
- regex.lastIndex++;
394
- }
395
-
396
- let main = m[0];
397
-
398
- const replaceStart = new RegExp('#\\{\\{' + blockName + '\\}\\}', 'gm');
399
- main = main.replace(replaceStart, contentBefore);
400
-
401
- const replaceEnd = new RegExp('#\\{\\{' + blockName + '\\/\\}\\}', 'gm');
402
- main = main.replace(replaceEnd, contentAfter);
403
-
404
- main = block.custom(main);
405
- ctx = ctx.replace(m[0], main);
406
- }
407
-
416
+ ctx = ctx.replace(regex, (_match, content: string) => block.custom(contentBefore + content + contentAfter));
408
417
  }
409
418
  return ctx;
410
419
  }
@@ -426,6 +435,10 @@ export abstract class AventusTemplate {
426
435
  }
427
436
  }
428
437
 
438
+ protected async aventusCommand(cmd: string, args?: any[]): Promise<void> {
439
+ await this.runCommand("aventusCommand", { command: cmd, arguments: args });
440
+ }
441
+
429
442
  protected showErrorMessage(msg: string): void {
430
443
  return this.runCommand("showErrorMessage", msg);
431
444
  }
@@ -433,10 +446,10 @@ export abstract class AventusTemplate {
433
446
  return this.runCommand("showWarningMessage", msg);
434
447
  }
435
448
  protected showInformationMessage(msg: string): void {
436
- return this.runCommand("showErrorMessage", msg);
449
+ return this.runCommand("showInformationMessage", msg);
437
450
  }
438
451
  protected async showProgress(txt: string): Promise<string> {
439
- return await this.runCommandWithAnswer("progressStart", txt);
452
+ return (await this.runCommandWithAnswer("progressStart", txt))!;
440
453
  }
441
454
  protected async hideProgress(uuid: string): Promise<void> {
442
455
  await this.runCommand("progressStop", uuid);
@@ -2,7 +2,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
2
2
  `:`
3
3
  `)+n,i=r+1,r=e.indexOf(`
4
4
  `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:B,stderr:V}=le,H=Symbol(`GENERATOR`),U=Symbol(`STYLER`),W=Symbol(`IS_EMPTY`),G=[`ansi`,`ansi`,`ansi256`,`ansi16m`],K=Object.create(null),fe=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=B?B.level:0;e.level=t.level===void 0?n:t.level},pe=e=>{let t=(...e)=>e.join(` `);return fe(t,e),Object.setPrototypeOf(t,q.prototype),t};function q(e){return pe(e)}Object.setPrototypeOf(q.prototype,Function.prototype);for(let[e,t]of Object.entries(F))K[e]={get(){let n=X(this,Y(t.open,t.close,this[U]),this[W]);return Object.defineProperty(this,e,{value:n}),n}};K.visible={get(){let e=X(this,this[U],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const J=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?F[n].ansi16m(...r):t===`ansi256`?F[n].ansi256(F.rgbToAnsi256(...r)):F[n].ansi(F.rgbToAnsi(...r)):e===`hex`?J(`rgb`,t,n,...F.hexToRgb(...r)):F[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){K[e]={get(){let{level:t}=this;return function(...n){let r=Y(J(e,G[t],`color`,...n),F.color.close,this[U]);return X(this,r,this[W])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);K[t]={get(){let{level:t}=this;return function(...n){let r=Y(J(e,G[t],`bgColor`,...n),F.bgColor.close,this[U]);return X(this,r,this[W])}}}}const me=Object.defineProperties(()=>{},{...K,level:{enumerable:!0,get(){return this[H].level},set(e){this[H].level=e}}}),Y=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},X=(e,t,n)=>{let r=(...e)=>he(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,me),r[H]=e,r[U]=t,r[W]=n,r},he=(e,t)=>{if(e.level<=0||!t)return e[W]?``:t;let n=e[U];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=ue(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
5
- `);return a!==-1&&(t=de(t,i,r,a)),r+t+i};Object.defineProperties(q.prototype,K);const Z=q();q({level:V?V.level:0});function ge(e){return e.name===`escape`}function Q(e){return e.endsWith(f.sep)?e:`${e}${f.sep}`}function _e(e){return e.replace(/\x1B\[\d+m/g,``)}function ve(e){return e.reduce((e,t)=>Math.max(e,_e(t).length),0)}function ye(e){return(0,m.readdirSync)(e).map(t=>{let n=(0,f.join)(e,t),r=(0,m.statSync)(n);return Object.assign(r,{name:t,path:n,isDisabled:!1})})}function be(e,t){return e.sort((e,t)=>e.isDisabled&&!t.isDisabled?1:!e.isDisabled&&t.isDisabled||e.isDirectory()&&!t.isDirectory()?-1:!e.isDirectory()&&t.isDirectory()?1:e.name.localeCompare(t.name)).filter(e=>t||!e.isDisabled)}const xe={prefix:{idle:Z.cyan(`?`),done:Z.green(w.tick),canceled:Z.red(w.cross)},icon:{linePrefix:e=>e?`${w.lineUpRight}${w.line.repeat(2)} `:`${w.lineUpDownRight}${w.line.repeat(2)} `},style:{disabled:e=>Z.dim(e),active:e=>Z.cyan(e),cancelText:e=>Z.red(e),emptyText:e=>Z.red(e),directory:e=>Z.yellow(e),file:e=>Z.white(e),currentDir:e=>Z.magenta(e),message:(e,t)=>Z.bold(e),help:e=>Z.white(e),key:e=>Z.cyan(e)}};var Se=(0,l.createPrompt)((e,t)=>{let{type:n=`file`,pageSize:r=10,loop:i=!1,showExcluded:a=!1,disabledLabel:o=` (not allowed)`,allowCancel:s=!1,cancelText:c=`Canceled.`,emptyText:u=`Directory is empty.`}=e,[d,p]=(0,l.useState)(`idle`),m=(0,l.makeTheme)(xe,e.theme),h=(0,l.usePrefix)({status:d,theme:m}),[g,_]=(0,l.useState)((0,f.resolve)(process.cwd(),e.basePath||`.`)),v=(0,l.useMemo)(()=>{let t=ye(g);for(let n of t)n.isDisabled=e.filter?!e.filter(n):!1;return be(t,a)},[g]),y=(0,l.useMemo)(()=>{let e=v.findIndex(e=>!e.isDisabled),t=v.findLastIndex(e=>!e.isDisabled);return e===-1?{first:0,last:0}:{first:e,last:t}},[v]),[b,x]=(0,l.useState)(y.first),S=v[b];(0,l.useKeypress)((e,r)=>{if((0,l.isEnterKey)(e)){if(console.log(S.isDisabled),console.log(n),S.isDisabled||n===`file`&&S.isDirectory()||n===`directory`&&!S.isDirectory())return;p(`done`),t(S.path)}else if((0,l.isSpaceKey)(e)&&S.isDirectory())_(S.path),x(y.first);else if((0,l.isUpKey)(e)||(0,l.isDownKey)(e)){if(r.clearLine(0),i||(0,l.isUpKey)(e)&&b!==y.first||(0,l.isDownKey)(e)&&b!==y.last){let t=(0,l.isUpKey)(e)?-1:1,n=b;do n=(n+t+v.length)%v.length;while(v[n].isDisabled);x(n)}}else (0,l.isBackspaceKey)(e)?(_((0,f.resolve)(g,`..`)),x(y.first)):(ge(e)&&s||E(e))&&(p(`canceled`),t(null))});let C=(0,l.usePagination)({items:v,active:b,renderItem({item:e,index:t,isActive:n}){let r=t===v.length-1,i=m.icon.linePrefix(r),a=e.isDirectory()?`${i}${Q(e.name)}`:`${i}${e.name}`;if(e.isDisabled)return m.style.disabled(`${a}${o}`);let s=e.isDirectory()?m.style.directory:m.style.file;return(n?m.style.active:s)(a)},pageSize:r,loop:i}),T=m.style.message(e.message,d);if(d===`canceled`)return`${h} ${T} ${m.style.cancelText(c)}`;if(d===`done`)return`${h} ${T} ${m.style.answer(S.path)}`;let ee=m.style.currentDir(Q(g)),D=(0,l.useMemo)(()=>{let e=[`${m.style.key(w.arrowUp+w.arrowDown)} navigate, ${m.style.key(`<enter>`)} select${s?`, ${m.style.key(`<esc>`)} cancel`:``}`,`${m.style.key(`<space>`)} open directory, ${m.style.key(`<backspace>`)} go back`],t=ve(e);return`${w.lineBold.repeat(t)}\n${e.join(`
5
+ `);return a!==-1&&(t=de(t,i,r,a)),r+t+i};Object.defineProperties(q.prototype,K);const Z=q();q({level:V?V.level:0});function ge(e){return e.name===`escape`}function Q(e){return e.endsWith(f.sep)?e:`${e}${f.sep}`}function _e(e){return e.replace(/\x1B\[\d+m/g,``)}function ve(e){return e.reduce((e,t)=>Math.max(e,_e(t).length),0)}function ye(e){return(0,m.readdirSync)(e).map(t=>{let n=(0,f.join)(e,t),r=(0,m.statSync)(n);return Object.assign(r,{name:t,path:n,isDisabled:!1})})}function be(e,t){return e.sort((e,t)=>e.isDisabled&&!t.isDisabled?1:!e.isDisabled&&t.isDisabled||e.isDirectory()&&!t.isDirectory()?-1:!e.isDirectory()&&t.isDirectory()?1:e.name.localeCompare(t.name)).filter(e=>t||!e.isDisabled)}const xe={prefix:{idle:Z.cyan(`?`),done:Z.green(w.tick),canceled:Z.red(w.cross)},icon:{linePrefix:e=>e?`${w.lineUpRight}${w.line.repeat(2)} `:`${w.lineUpDownRight}${w.line.repeat(2)} `},style:{disabled:e=>Z.dim(e),active:e=>Z.cyan(e),cancelText:e=>Z.red(e),emptyText:e=>Z.red(e),directory:e=>Z.yellow(e),file:e=>Z.white(e),currentDir:e=>Z.magenta(e),message:(e,t)=>Z.bold(e),help:e=>Z.white(e),key:e=>Z.cyan(e)}};var Se=(0,l.createPrompt)((e,t)=>{let{type:n=`file`,pageSize:r=10,loop:i=!1,showExcluded:a=!1,disabledLabel:o=` (not allowed)`,allowCancel:s=!1,cancelText:c=`Canceled.`,emptyText:u=`Directory is empty.`}=e,[d,p]=(0,l.useState)(`idle`),m=(0,l.makeTheme)(xe,e.theme),h=(0,l.usePrefix)({status:d,theme:m}),[g,_]=(0,l.useState)((0,f.resolve)(process.cwd(),e.basePath||`.`)),v=(0,l.useMemo)(()=>{let t=ye(g);for(let n of t)n.isDisabled=e.filter?!e.filter(n):!1;return be(t,a)},[g]),y=(0,l.useMemo)(()=>{let e=v.findIndex(e=>!e.isDisabled),t=v.findLastIndex(e=>!e.isDisabled);return e===-1?{first:0,last:0}:{first:e,last:t}},[v]),[b,x]=(0,l.useState)(y.first),S=v[b];(0,l.useKeypress)((e,r)=>{if((0,l.isEnterKey)(e)){if(S.isDisabled||n===`file`&&S.isDirectory()||n===`directory`&&!S.isDirectory())return;p(`done`),t(S.path)}else if((0,l.isSpaceKey)(e)&&S.isDirectory())_(S.path),x(y.first);else if((0,l.isUpKey)(e)||(0,l.isDownKey)(e)){if(r.clearLine(0),i||(0,l.isUpKey)(e)&&b!==y.first||(0,l.isDownKey)(e)&&b!==y.last){let t=(0,l.isUpKey)(e)?-1:1,n=b;do n=(n+t+v.length)%v.length;while(v[n].isDisabled);x(n)}}else (0,l.isBackspaceKey)(e)?(_((0,f.resolve)(g,`..`)),x(y.first)):(ge(e)&&s||E(e))&&(p(`canceled`),t(null))});let C=(0,l.usePagination)({items:v,active:b,renderItem({item:e,index:t,isActive:n}){let r=t===v.length-1,i=m.icon.linePrefix(r),a=e.isDirectory()?`${i}${Q(e.name)}`:`${i}${e.name}`;if(e.isDisabled)return m.style.disabled(`${a}${o}`);let s=e.isDirectory()?m.style.directory:m.style.file;return(n?m.style.active:s)(a)},pageSize:r,loop:i}),T=m.style.message(e.message,d);if(d===`canceled`)return`${h} ${T} ${m.style.cancelText(c)}`;if(d===`done`)return`${h} ${T} ${m.style.answer(S.path)}`;let ee=m.style.currentDir(Q(g)),D=(0,l.useMemo)(()=>{let e=[`${m.style.key(w.arrowUp+w.arrowDown)} navigate, ${m.style.key(`<enter>`)} select${s?`, ${m.style.key(`<esc>`)} cancel`:``}`,`${m.style.key(`<space>`)} open directory, ${m.style.key(`<backspace>`)} go back`],t=ve(e);return`${w.lineBold.repeat(t)}\n${e.join(`
6
6
  `)}`},[]);return`${h} ${T}\n${ee}\n${C.length?C:m.style.emptyText(u)}\n${D}[?25l`}),Ce=(0,l.createPrompt)((e,t)=>{let{required:n,validate:r=()=>!0}=e,i=(0,l.makeTheme)(e.theme),[a,o]=(0,l.useState)(`idle`),[s=``,c]=(0,l.useState)(e.default),[u,d]=(0,l.useState)(),[f,p]=(0,l.useState)(``),m=(0,l.usePrefix)({status:a,theme:i});(0,l.useKeypress)(async(e,i)=>{if(a===`idle`)if((0,l.isEnterKey)(e)){let e=f||s;o(`loading`);let a=n&&!e?`You must provide a value`:await r(e);a===!0?(p(e),o(`done`),t(e)):(i.write(f),d(a||`You must provide a valid value`),o(`idle`))}else (0,l.isBackspaceKey)(e)&&!f?c(void 0):e.name===`tab`&&!f?(c(void 0),i.clearLine(0),i.write(s),p(s)):E(e)?(o(`done`),t(null)):(p(i.line),d(void 0))});let h=i.style.message(e.message,a),g=f;typeof e.transformer==`function`?g=e.transformer(f,{isFinal:a===`done`}):a===`done`&&(g=i.style.answer(f));let _;s&&a!==`done`&&!f&&(_=i.style.defaultAnswer(s));let v=``;return u&&(v=i.style.error(u)),[[m,h,_,g].filter(e=>e!==void 0).join(` `),v]}),we=(0,l.createPrompt)((e,t)=>{let[n,r]=(0,l.useState)({...e.errors[``]??{}});(0,l.useEffect)(()=>{let t,n=g.AsyncResource.bind(()=>{r({...e.errors[``]??{}})});return clearTimeout(t),t=setTimeout(()=>{e.refresh(n)},300),()=>{clearTimeout(t),e.stopRefresh(n)}},[e]);let i=(0,l.useMemo)(()=>{let e=[],t=n;for(let n in t)for(let r of t[n]){let t=``;switch(r.severity){case h.DiagnosticSeverity.Error:t=`\x1B[31m[error]\x1B[0m`;break;case h.DiagnosticSeverity.Warning:t=`\x1B[33m[warning]\x1B[0m`;break;case h.DiagnosticSeverity.Information:t=`\x1B[34m[info]\x1B[0m`;break;case h.DiagnosticSeverity.Hint:t=`\x1B[90m[hint]\x1B[0m`;continue}e.push(`${n}:${r.range.start.line+1} - ${t} : ${r.message}`)}return e.length===0?`No error`:e.join(`
7
7
  `)},[n]);return(0,l.useKeypress)(async(e,n)=>{E(e)&&t()}),i});const Te={icon:{cursor:w.pointer},style:{disabled:e=>_.default.dim(`- ${e}`),description:e=>_.default.cyan(e)},helpMode:`auto`};function $(e){return!l.Separator.isSeparator(e)&&!e.disabled}function Ee(e){return e.map(e=>{if(l.Separator.isSeparator(e))return e;if(typeof e==`string`)return{value:e,name:e,short:e,disabled:!1};let t=e.name??String(e.value);return{value:e.value,name:t,description:e.description,short:e.short??t,disabled:e.disabled??!1}})}var De=(0,l.createPrompt)((e,t)=>{let{loop:n=!0,pageSize:r=7}=e,i=(0,l.useRef)(!0),a=(0,l.makeTheme)(Te,e.theme),[o,s]=(0,l.useState)(`idle`),c=(0,l.usePrefix)({status:o,theme:a}),u=(0,l.useRef)(),d=(0,l.useMemo)(()=>Ee(e.choices),[e.choices]),f=(0,l.useMemo)(()=>{let e=d.findIndex($),t=d.findLastIndex($);if(e===-1)throw new l.ValidationError(`[select prompt] No selectable choices. All choices are disabled.`);return{first:e,last:t}},[d]),p=(0,l.useMemo)(()=>`default`in e?d.findIndex(t=>$(t)&&t.value===e.default):-1,[e.default,d]),[m,h]=(0,l.useState)(p===-1?f.first:p),g=d[m];(0,l.useKeypress)((e,r)=>{if(clearTimeout(u.current),(0,l.isEnterKey)(e))s(`done`),t(g.value);else if((0,l.isUpKey)(e)||(0,l.isDownKey)(e)){if(r.clearLine(0),n||(0,l.isUpKey)(e)&&m!==f.first||(0,l.isDownKey)(e)&&m!==f.last){let t=(0,l.isUpKey)(e)?-1:1,n=m;do n=(n+t+d.length)%d.length;while(!$(d[n]));h(n)}}else if((0,l.isNumberKey)(e)){r.clearLine(0);let t=Number(e.name)-1,n=d[t];n!=null&&$(n)&&h(t)}else if((0,l.isBackspaceKey)(e))r.clearLine(0);else if(E(e))s(`done`),t(null);else{let e=r.line.toLowerCase(),t=d.findIndex(t=>l.Separator.isSeparator(t)||!$(t)?!1:t.name.toLowerCase().startsWith(e));t!==-1&&h(t),u.current=setTimeout(()=>{r.clearLine(0)},700)}}),(0,l.useEffect)(()=>()=>{clearTimeout(u.current)},[]);let _=a.style.message(e.message,o),v=``,y=``;(a.helpMode===`always`||a.helpMode===`auto`&&i.current)&&(i.current=!1,d.length>r?y=`\n${a.style.help(`(Use arrow keys to reveal more choices)`)}`:v=a.style.help(`(Use arrow keys)`));let b=(0,l.usePagination)({items:d,active:m,renderItem({item:e,isActive:t}){if(l.Separator.isSeparator(e))return` ${e.separator}`;if(e.disabled){let t=typeof e.disabled==`string`?e.disabled:`(disabled)`;return a.style.disabled(`${e.name} ${t}`)}return(t?a.style.highlight:e=>e)(`${t?a.icon.cursor:` `} ${e.name}`)},pageSize:r,loop:n});if(o===`done`)return`${c} ${_} ${a.style.answer(g.short)}`;let x=g.description?`\n${a.style.description(g.description)}`:``;return`${[c,_,v].filter(Boolean).join(` `)}\n${b}${y}${x}${T.default.cursorHide}`});const Oe=[` /\\ | | `,` / \\ __ __ ___ _ __ | |_ _ _ ___ `,` / /\\ \\\\ \\ / // _ \\| _ \\ | __|| | | |/ __|`,` / ____ \\\\ V /| __/| | | || |_ | |_| |\\__ \\`,` /_/ \\_\\\\_/ \\___||_| |_| \\__| \\____||___/`];function ke(){console.log(`\x1B[31m`),console.log(Oe.join(`
8
8
  `)),console.log(`\x1B[0m`)}var Ae=(0,l.createPrompt)((e,t)=>{let{validate:n=()=>!0}=e,r=(0,l.makeTheme)(e.theme),[i,a]=(0,l.useState)(`idle`),[o,s]=(0,l.useState)(),[c,u]=(0,l.useState)(``),d=(0,l.usePrefix)({status:i,theme:r});(0,l.useKeypress)(async(e,r)=>{if(i===`idle`)if((0,l.isEnterKey)(e)){let e=c;a(`loading`);let i=await n(e);i===!0?(u(e),a(`done`),t(e)):(r.write(c),s(i||`You must provide a valid value`),a(`idle`))}else u(r.line),s(void 0)});let f=r.style.message(e.message,i),p=``,m;e.mask?p=(typeof e.mask==`string`?e.mask:`*`).repeat(c.length):i!==`done`&&(m=`${r.style.help(`[input is masked]`)}[?25l`),i===`done`&&(p=r.style.answer(p));let h=``;return o&&(h=r.style.error(o)),[[d,f,e.mask?p:m].join(` `),h]}),je=class{static _server;static get server(){return this._server}static config={clear:!1,printLogo:!1};static clear(){this.config.clear&&console.clear(),this.config.printLogo&&ke()}static async select(e,t){if(t.length==0)return console.error(`No choice available`),null;let n=await De({message:e,choices:t});return this.clear(),n}static async selectMultiple(e,t){let n=await A({message:e,choices:t});return this.clear(),n}static async input(e,t,n){n||=()=>!0,t||=``;let r=await Ce({message:e,default:t,validate:n});return this.clear(),r}static async password(e,t){t||=()=>!0;let n=await Ae({message:e,validate:t});return this.clear(),n}static async tree(e,t,n){let r;t==`directory`&&(r=e=>e.isDirectory());let i=await Se({message:e,basePath:n,type:t,filter:r});return this.clear(),i}static async log(){await we({errors:this.server.getErrors(),refresh:e=>{this.server.subscribeErrors(e)},stopRefresh:e=>{this.server.unsubscribeErrors(e)}})}};exports.RealInteraction=je;