Skip to content

Instantly share code, notes, and snippets.

@PotOfCoffee2Go
Created November 17, 2023 05:02
Show Gist options
  • Save PotOfCoffee2Go/6aec631ee9ea3862a32308778bfe5517 to your computer and use it in GitHub Desktop.
Save PotOfCoffee2Go/6aec631ee9ea3862a32308778bfe5517 to your computer and use it in GitHub Desktop.
TW5 modules to implement REPL
created: 20231116150029494
modified: 20231117043247159
module-type: command
tags:
title: $:/poc2go/modules/commands/repl.js
type: application/javascript
/*\
title: $:/poc2go/modules/commands/repl.js
type: application/javascript
module-type: command
node.js REPL with access to $tw
Optional params = REPL prompt
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "repl",
synchronous: true
};
var Command = function(params,commander,callback) {
var self = this;
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
var self = this;
// Only allow a single REPL instance
if (!$tw.repl) {
$tw.repl = new $tw.Repl(this.params.length ? this.params[0] : '$tw-repl> ')
}
// If REPL is reset (.clear) - context needs resetting
$tw.repl.on('reset', function() {
$tw.repl.context.$tw = $tw;
});
// Initial context settings
$tw.repl.context.$tw = $tw;
return null;
};
exports.Command = Command;
})();
created: 20231117022506498
modified: 20231117041431381
module-type: global
tags:
title: $:/poc2go/modules/repl.js
type: application/javascript
/*\
title: $:/po2go/modules/repl.js
type: application/javascript
module-type: global
node.js REPL runtime interface
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Usage:
if (!$tw.repl) { new Repl(options) }
$tw.repl.context.objRef = objRef;
$tw.repl.close() // !!! do not close - $tw.repl is a shared resource
*/
/*
Instantiate:
$tw.repl is assigned to REPL runtime
If options is typeof 'string' sets the prompt, all defaults are used
Returns $tw.repl
Options and defaults:
{
prompt: '$tw-repl> ',
useColors: true, // use Terminal colors
ignoreUndefined: true, // do not display annoying 'undefined' messages
// completer: autocompletion values - no defaults
}
*/
function Repl(options) {
// REPL is a singleton - return current reference
if ($tw.repl) { return $tw.repl }
// Options is the REPL prompt
if (typeof options === 'string') {
options = {
prompt: options
}
}
// Default settings
var defaultOptions = {
prompt: '$tw-repl> ',
useColors: true,
ignoreUndefined: true,
/*completer: completer*/
};
// Merge options with the defaults
var startOptions = Object.assign({}, defaultOptions, options);
// Start REPL and assign to $tw
$tw.repl = require('node:repl').start(startOptions);
return $tw.repl;
}
exports.Repl = Repl;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment