async repl()

in packages/sqrl-cli/src/repl/SqrlRepl.ts [57:112]


  async repl(ctx: Context, input: string): Promise<any> {
    let returnFeature = null;

    if (isValidFeatureName(input.trim())) {
      returnFeature = input.trim();
    } else {
      const ast = parseRepl(input, {
        customFunctions: this.instance._instance.customFunctions,
      });
      const statements = ast.statements;
      if (!statements.length) {
        return;
      }

      // If the last statement is an expression, save its result in SqrlReplOutput
      let last: Ast = statements[statements.length - 1];

      // If it's a call, make sure it's to a statement otherwise treat as an expression
      if (last.type === "call") {
        if (
          this.instance._instance.has(last.func) &&
          !this.instance._instance.isStatement(last.func)
        ) {
          last = {
            type: "expr",
            location: last.location,
            expr: last,
          };
        }
      }

      if (last.type === "let") {
        returnFeature = last.feature;
      } else if (last.type === "expr") {
        statements.pop();
        const { expr, location } = last;
        statements.push(
          SqrlAst.letStatement("SqrlReplOutput", expr, {
            description: null,
            location,
          })
        );
        returnFeature = "SqrlReplOutput";
      }

      // @NOTE: Only the last statement could be an Expr and that is handled
      // above. Newer TypeScript version may be able to handle this constraint
      // without a cast.
      await this.test.runStatements(ctx, statements as StatementAst[]);
    }

    if (returnFeature) {
      const state = await this.test.executeStatements(ctx, []);
      return state.fetchByName(returnFeature);
    }
  }