copying eixogen
commit
b00d9f80ed
@ -0,0 +1,243 @@
|
|||||||
|
var http = require('http');
|
||||||
|
var fs = require('fs');
|
||||||
|
var express = require('express');
|
||||||
|
var app = express();
|
||||||
|
var path = require('path');
|
||||||
|
var server = http.createServer(app);
|
||||||
|
var port = 8000;
|
||||||
|
var osc = require('osc');
|
||||||
|
var activeUsers = new Set(); // Active users Set
|
||||||
|
var name = [];
|
||||||
|
|
||||||
|
var udpPort = new osc.UDPPort({
|
||||||
|
// This is the port we're listening on.
|
||||||
|
localAddress: "0.0.0.0",
|
||||||
|
localPort: 57121,
|
||||||
|
|
||||||
|
// This is where sclang is listening for OSC messages.
|
||||||
|
remoteAddress: "192.168.2.5", //this is the hamsters ip
|
||||||
|
remotePort: 8080, //this is the hamsters port :*s
|
||||||
|
metadata: true
|
||||||
|
});
|
||||||
|
|
||||||
|
var trashcan = new osc.UDPPort({
|
||||||
|
// This is the port we're listening on.
|
||||||
|
localAddress: "0.0.0.0",
|
||||||
|
localPort: 57122,
|
||||||
|
|
||||||
|
// This is where sclang is listening for OSC messages.
|
||||||
|
remoteAddress: "192.168.2.21", //this is the trashc an ip
|
||||||
|
remotePort: 8888, //this is the trashcan port :*s
|
||||||
|
metadata: true
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// Open the socket.
|
||||||
|
udpPort.open();
|
||||||
|
trashcan.open();
|
||||||
|
|
||||||
|
const { SerialPort } = require('serialport')
|
||||||
|
const { ReadlineParser } = require('@serialport/parser-readline')
|
||||||
|
const sport = new SerialPort({ path: '/dev/ttyACM0', baudRate: 115200 })
|
||||||
|
|
||||||
|
const parser = sport.pipe(new ReadlineParser({ delimiter: '\r\n' }))
|
||||||
|
|
||||||
|
server.listen(port, () => {
|
||||||
|
console.log("Server is listening at port %d", port);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(express.static(path.join(__dirname, "public")));
|
||||||
|
|
||||||
|
var io = require('socket.io')(server);
|
||||||
|
|
||||||
|
io.on('connection', function(socket) {
|
||||||
|
console.log("new user online!");
|
||||||
|
|
||||||
|
// Add the new socket ID to the activeUsers Set
|
||||||
|
activeUsers.add(socket.id);
|
||||||
|
|
||||||
|
// Emit the updated activeUsers Set to all connected clients
|
||||||
|
io.emit('activeUsers', Array.from(activeUsers));
|
||||||
|
|
||||||
|
parser.on('data', function(data) {
|
||||||
|
const msg = data.split(' ');
|
||||||
|
console.log(msg[0], msg[1]);
|
||||||
|
io.emit('node-data', data);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("blink", () => {
|
||||||
|
console.log("Blink event received!");
|
||||||
|
io.emit("blink"); // Emit the "blink" event to all connected clients
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
socket.on('chat message', (msg) => {
|
||||||
|
console.log('[user][' + socket.id + '][' + msg + ']');
|
||||||
|
socket.broadcast.emit('chat message', msg);
|
||||||
|
|
||||||
|
var oscmsg = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: socket.id
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: msg
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(oscmsg);
|
||||||
|
|
||||||
|
|
||||||
|
if (msg == "9292") {
|
||||||
|
console.log('secret trash received');
|
||||||
|
var oscmsg = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: msg
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
trashcan.send(oscmsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg == "comp") {
|
||||||
|
console.log('comp received');
|
||||||
|
var hampctrl = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: "comp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(hampctrl);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg == "off") {
|
||||||
|
console.log('off received');
|
||||||
|
var hampctrl = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: "off"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(hampctrl);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
var oscmsg = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: socket.id
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: msg
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(oscmsg);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
app.post('/trash', (req, res) => {
|
||||||
|
console.log('9292 received');
|
||||||
|
var hampctrl = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: "9292"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
trashcan.send(hampctrl);
|
||||||
|
|
||||||
|
// Send a response back to the client
|
||||||
|
res.status(200).send("OSC message sent to trash");
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
app.post('/hamp-off', (req, res) => {
|
||||||
|
console.log('off received');
|
||||||
|
var hampctrl = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: "off"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(hampctrl);
|
||||||
|
|
||||||
|
// Send a response back to the client
|
||||||
|
res.status(200).send("OSC message sent");
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/hamp-on', (req, res) => {
|
||||||
|
console.log('on received');
|
||||||
|
var hampctrl = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: "comp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(hampctrl);
|
||||||
|
|
||||||
|
// Send a response back to the client
|
||||||
|
res.status(200).send("OSC message sent");
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
socket.on('userposition', (msg) => {
|
||||||
|
console.log('[user][' + socket.id + '][position: ' + msg[0] + ',' + msg[1] + ']');
|
||||||
|
socket.to('expo').emit(socket.id, msg);
|
||||||
|
});
|
||||||
|
|
||||||
|
// socket.on('name', (msg)=> {
|
||||||
|
// console.log("[name]["+socket.id +"]["+ msg +"]");
|
||||||
|
// name.push({ id: socket.id, name: msg }); // Push an object with user ID and name
|
||||||
|
// console.log(name);
|
||||||
|
// });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Handle disconnection event
|
||||||
|
socket.on('disconnect', () => {
|
||||||
|
console.log("new user online:", socket.id);
|
||||||
|
|
||||||
|
// Remove the disconnected socket ID from the activeUsers Set
|
||||||
|
activeUsers.delete(socket.id);
|
||||||
|
|
||||||
|
// Emit the updated activeUsers Set to all connected clients
|
||||||
|
io.emit('activeUsers', Array.from(activeUsers));
|
||||||
|
});
|
||||||
|
});
|
@ -0,0 +1,162 @@
|
|||||||
|
var http = require('http');
|
||||||
|
var php = require('php');
|
||||||
|
var fs = require('fs');
|
||||||
|
var phpExpress = require('php-express')({
|
||||||
|
binPath: 'php'
|
||||||
|
});
|
||||||
|
var express = require('express');
|
||||||
|
var app = express();
|
||||||
|
var path = require('path');
|
||||||
|
var server = http.createServer(app);
|
||||||
|
//var server = http.createServer(php);
|
||||||
|
//var port = 8000;
|
||||||
|
var osc = require('osc');
|
||||||
|
var activeUsers = new Set(); // Active users Set
|
||||||
|
|
||||||
|
|
||||||
|
/////////////////////////////////////////////////////// php
|
||||||
|
var router = express.Router();
|
||||||
|
var bodyParser = require('body-parser');
|
||||||
|
|
||||||
|
app.use(bodyParser.json());
|
||||||
|
|
||||||
|
app.set('port', (process.env.PORT || 8000));
|
||||||
|
|
||||||
|
//app.get('/',function(req,res){
|
||||||
|
// res.sendFile(path.join(__dirname, 'public', 'index.php'));
|
||||||
|
//});
|
||||||
|
|
||||||
|
app.use('/', express.static(__dirname));
|
||||||
|
app.set('public', path.join(__dirname, '/public'));
|
||||||
|
app.engine('php', phpExpress.engine);
|
||||||
|
app.set('view engine', 'php');
|
||||||
|
|
||||||
|
app.all(/.+\.php$/, phpExpress.router);
|
||||||
|
|
||||||
|
app.use(function (req, res, next) {
|
||||||
|
res.status(404).send("Sorry can't find that!")
|
||||||
|
});
|
||||||
|
|
||||||
|
app.listen(app.get('port'), function() {
|
||||||
|
console.log('Node app is running on port', app.get('port'));
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//server.listen(port, () => {
|
||||||
|
// console.log("Server is listening at port %d", port);
|
||||||
|
//});
|
||||||
|
|
||||||
|
//app.use(express.static(path.join(__dirname, "public")));
|
||||||
|
//app.use(express.static('public'));
|
||||||
|
|
||||||
|
|
||||||
|
//var server = app.listen(8000, function() {
|
||||||
|
// console.log('listening on requests on port 8000');
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//app.get('/',function(req,res){
|
||||||
|
// res.sendFile(path.join(__dirname, 'public', 'index.php'));
|
||||||
|
//});
|
||||||
|
|
||||||
|
//app.set('views', __dirname+'public');
|
||||||
|
//app.engine('php', phpExpress.engine);
|
||||||
|
|
||||||
|
//app.all('/index.php', function(req, res) {
|
||||||
|
// res.render('phpinfo');
|
||||||
|
//})
|
||||||
|
//app.all(/.+\.php$/, phpExpress.router);
|
||||||
|
|
||||||
|
//Static files
|
||||||
|
//app.use(express.static('public'));
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
|
||||||
|
var udpPort = new osc.UDPPort({
|
||||||
|
// This is the port we're listening on.
|
||||||
|
localAddress: "0.0.0.0",
|
||||||
|
localPort: 57121,
|
||||||
|
|
||||||
|
// This is where sclang is listening for OSC messages.
|
||||||
|
remoteAddress: "192.168.2.15", //this is the hamsters ip
|
||||||
|
remotePort: 8080, //this is the hamsters port :*s
|
||||||
|
metadata: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Open the socket.
|
||||||
|
udpPort.open();
|
||||||
|
|
||||||
|
const { SerialPort } = require('serialport')
|
||||||
|
const { ReadlineParser } = require('@serialport/parser-readline')
|
||||||
|
const sport = new SerialPort({ path: '/dev/ttyACM0', baudRate: 115200 })
|
||||||
|
|
||||||
|
const parser = sport.pipe(new ReadlineParser({ delimiter: '\r\n' }))
|
||||||
|
|
||||||
|
//server.listen(port, () => {
|
||||||
|
// console.log("Server is listening at port %d", port);
|
||||||
|
//});
|
||||||
|
|
||||||
|
//app.use(express.static(path.join(__dirname, "public")));
|
||||||
|
//app.use(express.static('public'));
|
||||||
|
|
||||||
|
|
||||||
|
var io = require('socket.io')(server);
|
||||||
|
|
||||||
|
io.on('connection', function(socket) {
|
||||||
|
console.log("new user online!");
|
||||||
|
|
||||||
|
// Add the new socket ID to the activeUsers Set
|
||||||
|
activeUsers.add(socket.id);
|
||||||
|
|
||||||
|
// Emit the updated activeUsers Set to all connected clients
|
||||||
|
io.emit('activeUsers', Array.from(activeUsers));
|
||||||
|
|
||||||
|
parser.on('data', function(data) {
|
||||||
|
const msg = data.split(' ');
|
||||||
|
console.log(msg[0], msg[1]);
|
||||||
|
io.emit('node-data', data);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("blink", () => {
|
||||||
|
console.log("Blink event received!");
|
||||||
|
io.emit("blink"); // Emit the "blink" event to all connected clients
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('chat message', (msg) => {
|
||||||
|
console.log('[user][' + socket.id + '][' + msg + ']');
|
||||||
|
socket.broadcast.emit('chat message', msg);
|
||||||
|
|
||||||
|
var oscmsg = {
|
||||||
|
address: "/silentserver",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: socket.id
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "s",
|
||||||
|
value: msg
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
udpPort.send(oscmsg);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('userposition', (msg) => {
|
||||||
|
console.log('[user][' + socket.id + '][position: ' + msg[0] + ',' + msg[1] + ']');
|
||||||
|
socket.to('expo').emit(socket.id, msg);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle disconnection event
|
||||||
|
socket.on('disconnect', () => {
|
||||||
|
console.log("new user online:", socket.id);
|
||||||
|
|
||||||
|
// Remove the disconnected socket ID from the activeUsers Set
|
||||||
|
activeUsers.delete(socket.id);
|
||||||
|
|
||||||
|
// Emit the updated activeUsers Set to all connected clients
|
||||||
|
io.emit('activeUsers', Array.from(activeUsers));
|
||||||
|
});
|
||||||
|
});
|
@ -0,0 +1,54 @@
|
|||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
#include <WebSocketsClient.h>
|
||||||
|
|
||||||
|
const char* ssid = "Ether Axis";
|
||||||
|
const char* password = "WanderingWebWizard";
|
||||||
|
|
||||||
|
WebSocketsClient webSocket;
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// Initialize the serial communication
|
||||||
|
Serial.begin(9600);
|
||||||
|
|
||||||
|
// Connect to Wi-Fi network
|
||||||
|
WiFi.begin(ssid, password);
|
||||||
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
|
delay(1000);
|
||||||
|
Serial.println("Connecting to WiFi...");
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("Connected to WiFi!");
|
||||||
|
|
||||||
|
// Set up event handlers
|
||||||
|
webSocket.onEvent(onWebSocketEvent);
|
||||||
|
|
||||||
|
// Connect to the WebSocket server
|
||||||
|
webSocket.begin("192.168.2.1", 8000, "/socket.io/?transport=websocket");
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Maintain the WebSocket connection
|
||||||
|
webSocket.loop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void onWebSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
|
||||||
|
switch (type) {
|
||||||
|
case WStype_DISCONNECTED:
|
||||||
|
Serial.println("[WebSocket] Disconnected!");
|
||||||
|
break;
|
||||||
|
case WStype_CONNECTED:
|
||||||
|
Serial.println("[WebSocket] Connected!");
|
||||||
|
break;
|
||||||
|
case WStype_TEXT:
|
||||||
|
Serial.println("[WebSocket] Text received!");
|
||||||
|
Serial.write(payload, length);
|
||||||
|
|
||||||
|
// Check if the received message is the "blink" event
|
||||||
|
if (strncmp((const char*)payload, "blink", length) == 0) {
|
||||||
|
// Perform the desired action for the "blink" event
|
||||||
|
Serial.println("Received blink event!");
|
||||||
|
// Add your code here to trigger the blink action
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
#include <SPI.h>
|
||||||
|
#include <LoRa.h>
|
||||||
|
|
||||||
|
#define LORA_SS_PIN 10
|
||||||
|
#define LORA_RST_PIN 9
|
||||||
|
#define LORA_DI0_PIN 2
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(9600);
|
||||||
|
while (!Serial);
|
||||||
|
|
||||||
|
pinMode(LED_BUILTIN, OUTPUT);
|
||||||
|
|
||||||
|
// Initialize LoRa module
|
||||||
|
LoRa.setPins(LORA_SS_PIN, LORA_RST_PIN, LORA_DI0_PIN);
|
||||||
|
if (!LoRa.begin(433E6)) {
|
||||||
|
Serial.println("LoRa initialization failed. Check your wiring!");
|
||||||
|
while (true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect to WiFi or Ethernet here
|
||||||
|
|
||||||
|
// Connect to Socket.IO server
|
||||||
|
// Replace <SERVER_ADDRESS> with the actual server address
|
||||||
|
// e.g., http://localhost:3000
|
||||||
|
// Replace <TOKEN> with an authentication token if required
|
||||||
|
// e.g., "?token=abcd1234"
|
||||||
|
//socketIO.connect("<SERVER_ADDRESS><TOKEN>");
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Handle Socket.IO events or other tasks here
|
||||||
|
|
||||||
|
// Check for incoming LoRa messages
|
||||||
|
int packetSize = LoRa.parsePacket();
|
||||||
|
if (packetSize) {
|
||||||
|
while (LoRa.available()) {
|
||||||
|
String message = LoRa.readString();
|
||||||
|
Serial.println("Received message: " + message);
|
||||||
|
|
||||||
|
// Process the received message and control the LED
|
||||||
|
if (message == "led_on") {
|
||||||
|
digitalWrite(LED_BUILTIN, HIGH); // Turn on the LED
|
||||||
|
LoRa.beginPacket();
|
||||||
|
LoRa.print("ack");
|
||||||
|
LoRa.endPacket();
|
||||||
|
} else if (message == "led_off") {
|
||||||
|
digitalWrite(LED_BUILTIN, LOW); // Turn off the LED
|
||||||
|
LoRa.beginPacket();
|
||||||
|
LoRa.print("ack");
|
||||||
|
LoRa.endPacket();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,57 @@
|
|||||||
|
|
||||||
|
#include <LoRa.h>
|
||||||
|
#include "boards.h"
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
|
||||||
|
initBoard();
|
||||||
|
// When the power is turned on, a delay is required.
|
||||||
|
delay(1500);
|
||||||
|
|
||||||
|
Serial.println("LoRa Receiver");
|
||||||
|
|
||||||
|
LoRa.setPins(RADIO_CS_PIN, RADIO_RST_PIN, RADIO_DI0_PIN);
|
||||||
|
if (!LoRa.begin(LoRa_frequency)) {
|
||||||
|
Serial.println("Starting LoRa failed!");
|
||||||
|
while (1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop()
|
||||||
|
{
|
||||||
|
// try to parse packet
|
||||||
|
int packetSize = LoRa.parsePacket();
|
||||||
|
if (packetSize) {
|
||||||
|
// received a packet
|
||||||
|
// Serial.print("Received packet '");
|
||||||
|
|
||||||
|
String recv = "";
|
||||||
|
// read packet
|
||||||
|
while (LoRa.available()) {
|
||||||
|
recv += (char)LoRa.read();
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println(recv);
|
||||||
|
|
||||||
|
// // print RSSI of packet
|
||||||
|
// Serial.print("' with RSSI ");
|
||||||
|
// Serial.println(LoRa.packetRssi());
|
||||||
|
////
|
||||||
|
|
||||||
|
#ifdef HAS_DISPLAY
|
||||||
|
if (u8g2) {
|
||||||
|
u8g2->clearBuffer();
|
||||||
|
char buf[256];
|
||||||
|
u8g2->drawStr(0, 12, "Received OK!");
|
||||||
|
u8g2->drawStr(0, 26, recv.c_str());
|
||||||
|
snprintf(buf, sizeof(buf), "RSSI:%i", LoRa.packetRssi());
|
||||||
|
u8g2->drawStr(0, 40, buf);
|
||||||
|
snprintf(buf, sizeof(buf), "SNR:%.1f", LoRa.packetSnr());
|
||||||
|
u8g2->drawStr(0, 56, buf);
|
||||||
|
u8g2->sendBuffer();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,85 @@
|
|||||||
|
#include <LoRa.h>
|
||||||
|
#include "boards.h"
|
||||||
|
#include <SafeString.h>
|
||||||
|
#include <millisDelay.h>
|
||||||
|
|
||||||
|
|
||||||
|
//elapsedMillis timeElapsed;
|
||||||
|
//unsigned int interval = 20000;
|
||||||
|
millisDelay codetimer;
|
||||||
|
int counter = 0;
|
||||||
|
int percent = 0;
|
||||||
|
int prevPercent = 0;
|
||||||
|
long futuretime = 0;
|
||||||
|
long timetowait = 1000 * 3; //thelast number is the seconds
|
||||||
|
int secretcode = 21;
|
||||||
|
int addedRandom = 0;
|
||||||
|
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
Serial.begin( 9600 );
|
||||||
|
initBoard();
|
||||||
|
// When the power is turned on, a delay is required.
|
||||||
|
delay(1500);
|
||||||
|
Serial.println("LoRa Sender");
|
||||||
|
LoRa.setPins(RADIO_CS_PIN, RADIO_RST_PIN, RADIO_DI0_PIN);
|
||||||
|
if (!LoRa.begin(LoRa_frequency)) {
|
||||||
|
Serial.println("Starting LoRa failed!");
|
||||||
|
while (1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop(){
|
||||||
|
percent = round(analogRead(2) / 4095.00 * 100 + addedRandom);
|
||||||
|
|
||||||
|
if(percent != prevPercent) {
|
||||||
|
Serial.println(percent);
|
||||||
|
LoRa.beginPacket();
|
||||||
|
LoRa.print("node4 ");
|
||||||
|
LoRa.print(percent);
|
||||||
|
LoRa.endPacket();
|
||||||
|
prevPercent = percent;
|
||||||
|
futuretime = millis() + timetowait; // current time plus the timetowait
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// delay(100);
|
||||||
|
// Serial.print("Sending packet: ");
|
||||||
|
// Serial.println(percent);
|
||||||
|
|
||||||
|
// send packet
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef HAS_DISPLAY
|
||||||
|
|
||||||
|
if (u8g2) {
|
||||||
|
char buf[256];
|
||||||
|
dtostrf(percent,3,0,buf);
|
||||||
|
u8g2->clearBuffer();
|
||||||
|
String message = String(percent);
|
||||||
|
u8g2->drawStr(0, 20, " Gateway code:");
|
||||||
|
// snprintf(buf, sizeof(buf), "Sending: %d", counter);
|
||||||
|
u8g2->drawStr(0, 40, buf);
|
||||||
|
if(futuretime > millis()){ // checks the current time with the future time -> count down
|
||||||
|
u8g2->drawStr(0, 60, " connecting...");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if(percent == secretcode && futuretime+10000 < millis()){
|
||||||
|
u8g2->drawStr(0, 60, " connecting...");
|
||||||
|
addedRandom = random(0,10);
|
||||||
|
}
|
||||||
|
|
||||||
|
else if(percent == secretcode && futuretime < millis()) {
|
||||||
|
u8g2->drawStr(0, 60, " PORT: 20.15.18");
|
||||||
|
}
|
||||||
|
// u8g2->print(percent);
|
||||||
|
u8g2->sendBuffer();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
counter++;
|
||||||
|
}
|
@ -0,0 +1,169 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include <SPI.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include "utilities.h"
|
||||||
|
|
||||||
|
#ifdef HAS_SDCARD
|
||||||
|
#include <SD.h>
|
||||||
|
#include <FS.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef HAS_DISPLAY
|
||||||
|
#include <U8g2lib.h>
|
||||||
|
U8G2_SSD1306_128X64_NONAME_F_HW_I2C *u8g2 = nullptr;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(LILYGO_TBeam_V1_0) || defined(LILYGO_TBeam_V1_1)
|
||||||
|
#include <axp20x.h>
|
||||||
|
AXP20X_Class PMU;
|
||||||
|
|
||||||
|
bool initPMU()
|
||||||
|
{
|
||||||
|
if (PMU.begin(Wire, AXP192_SLAVE_ADDRESS) == AXP_FAIL) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* The charging indicator can be turned on or off
|
||||||
|
* * * */
|
||||||
|
// PMU.setChgLEDMode(LED_BLINK_4HZ);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The default ESP32 power supply has been turned on,
|
||||||
|
* no need to set, please do not set it, if it is turned off,
|
||||||
|
* it will not be able to program
|
||||||
|
*
|
||||||
|
* PMU.setDCDC3Voltage(3300);
|
||||||
|
* PMU.setPowerOutPut(AXP192_DCDC3, AXP202_ON);
|
||||||
|
*
|
||||||
|
* * * */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Turn off unused power sources to save power
|
||||||
|
* **/
|
||||||
|
|
||||||
|
PMU.setPowerOutPut(AXP192_DCDC1, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_DCDC2, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO2, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO3, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_EXTEN, AXP202_OFF);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Set the power of LoRa and GPS module to 3.3V
|
||||||
|
**/
|
||||||
|
PMU.setLDO2Voltage(3300); //LoRa VDD
|
||||||
|
PMU.setLDO3Voltage(3300); //GPS VDD
|
||||||
|
PMU.setDCDC1Voltage(3300); //3.3V Pin next to 21 and 22 is controlled by DCDC1
|
||||||
|
|
||||||
|
PMU.setPowerOutPut(AXP192_DCDC1, AXP202_ON);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO2, AXP202_ON);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO3, AXP202_ON);
|
||||||
|
|
||||||
|
pinMode(PMU_IRQ, INPUT_PULLUP);
|
||||||
|
attachInterrupt(PMU_IRQ, [] {
|
||||||
|
// pmu_irq = true;
|
||||||
|
}, FALLING);
|
||||||
|
|
||||||
|
PMU.adc1Enable(AXP202_VBUS_VOL_ADC1 |
|
||||||
|
AXP202_VBUS_CUR_ADC1 |
|
||||||
|
AXP202_BATT_CUR_ADC1 |
|
||||||
|
AXP202_BATT_VOL_ADC1,
|
||||||
|
AXP202_ON);
|
||||||
|
|
||||||
|
PMU.enableIRQ(AXP202_VBUS_REMOVED_IRQ |
|
||||||
|
AXP202_VBUS_CONNECT_IRQ |
|
||||||
|
AXP202_BATT_REMOVED_IRQ |
|
||||||
|
AXP202_BATT_CONNECT_IRQ,
|
||||||
|
AXP202_ON);
|
||||||
|
PMU.clearIRQ();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void disablePeripherals()
|
||||||
|
{
|
||||||
|
PMU.setPowerOutPut(AXP192_DCDC1, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO2, AXP202_OFF);
|
||||||
|
PMU.setPowerOutPut(AXP192_LDO3, AXP202_OFF);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
#define initPMU()
|
||||||
|
#define disablePeripherals()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
SPIClass SDSPI(HSPI);
|
||||||
|
|
||||||
|
|
||||||
|
void initBoard()
|
||||||
|
{
|
||||||
|
Serial.begin(115200);
|
||||||
|
Serial.println("initBoard");
|
||||||
|
SPI.begin(RADIO_SCLK_PIN, RADIO_MISO_PIN, RADIO_MOSI_PIN);
|
||||||
|
Wire.begin(I2C_SDA, I2C_SCL);
|
||||||
|
|
||||||
|
#ifdef HAS_GPS
|
||||||
|
Serial1.begin(GPS_BAUD_RATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if OLED_RST
|
||||||
|
pinMode(OLED_RST, OUTPUT);
|
||||||
|
digitalWrite(OLED_RST, HIGH); delay(20);
|
||||||
|
digitalWrite(OLED_RST, LOW); delay(20);
|
||||||
|
digitalWrite(OLED_RST, HIGH); delay(20);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
initPMU();
|
||||||
|
|
||||||
|
#ifdef HAS_SDCARD
|
||||||
|
SDSPI.begin(SDCARD_SCLK, SDCARD_MISO, SDCARD_MOSI, SDCARD_CS);
|
||||||
|
if (!SD.begin(SDCARD_CS, SDSPI)) {
|
||||||
|
Serial.println("setupSDCard FAIL");
|
||||||
|
} else {
|
||||||
|
uint32_t cardSize = SD.cardSize() / (1024 * 1024);
|
||||||
|
Serial.print("setupSDCard PASS . SIZE = ");
|
||||||
|
Serial.print(cardSize);
|
||||||
|
Serial.println(" MB");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef BOARD_LED
|
||||||
|
/*
|
||||||
|
* T-BeamV1.0, V1.1 LED defaults to low level as trun on,
|
||||||
|
* so it needs to be forced to pull up
|
||||||
|
* * * * */
|
||||||
|
#if LED_ON == LOW
|
||||||
|
gpio_hold_dis(GPIO_NUM_4);
|
||||||
|
#endif
|
||||||
|
pinMode(BOARD_LED, OUTPUT);
|
||||||
|
digitalWrite(BOARD_LED, LED_ON);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef HAS_DISPLAY
|
||||||
|
Wire.beginTransmission(0x3C);
|
||||||
|
if (Wire.endTransmission() == 0) {
|
||||||
|
Serial.println("Started OLED");
|
||||||
|
u8g2 = new U8G2_SSD1306_128X64_NONAME_F_HW_I2C(U8G2_R0, U8X8_PIN_NONE);
|
||||||
|
u8g2->begin();
|
||||||
|
u8g2->clearBuffer();
|
||||||
|
u8g2->setFlipMode(0);
|
||||||
|
u8g2->setFontMode(1); // Transparent
|
||||||
|
u8g2->setDrawColor(1);
|
||||||
|
u8g2->setFontDirection(0);
|
||||||
|
u8g2->firstPage();
|
||||||
|
do {
|
||||||
|
u8g2->setFont(u8g2_font_inb19_mr);
|
||||||
|
u8g2->drawStr(0, 30, "LilyGo");
|
||||||
|
u8g2->drawHLine(2, 35, 47);
|
||||||
|
u8g2->drawHLine(3, 36, 47);
|
||||||
|
u8g2->drawVLine(45, 32, 12);
|
||||||
|
u8g2->drawVLine(46, 33, 12);
|
||||||
|
u8g2->setFont(u8g2_font_inb19_mf);
|
||||||
|
u8g2->drawStr(58, 60, "LoRa");
|
||||||
|
} while ( u8g2->nextPage() );
|
||||||
|
u8g2->sendBuffer();
|
||||||
|
u8g2->setFont(u8g2_font_fur11_tf);
|
||||||
|
delay(5000);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,100 @@
|
|||||||
|
#include <LoRa.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include "boards.h"
|
||||||
|
#include <PN532_I2C.h>
|
||||||
|
#include <PN532.h>
|
||||||
|
#include <NfcAdapter.h>
|
||||||
|
|
||||||
|
PN532_I2C pn532_i2c(Wire);
|
||||||
|
NfcAdapter nfc = NfcAdapter(pn532_i2c);
|
||||||
|
String tagId = "None";
|
||||||
|
String cleanString = "";
|
||||||
|
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
Serial.begin(9600);
|
||||||
|
Serial.println("System initialized");
|
||||||
|
nfc.begin();
|
||||||
|
|
||||||
|
initLoRa();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop()
|
||||||
|
{
|
||||||
|
readNFC();
|
||||||
|
if (!cleanString.isEmpty()) {
|
||||||
|
sendLoRaData(cleanString);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void initLoRa()
|
||||||
|
{
|
||||||
|
Serial.println("Initializing LoRa...");
|
||||||
|
LoRa.setPins(RADIO_CS_PIN, RADIO_RST_PIN, RADIO_DI0_PIN);
|
||||||
|
if (!LoRa.begin(LoRa_frequency))
|
||||||
|
{
|
||||||
|
Serial.println("Starting LoRa failed!");
|
||||||
|
while (1);
|
||||||
|
}
|
||||||
|
Serial.println("LoRa initialized successfully!");
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendLoRaData(String data)
|
||||||
|
{
|
||||||
|
String message = "node3 " + data; // Concatenate "node3 " with the value of cleanString
|
||||||
|
|
||||||
|
LoRa.beginPacket();
|
||||||
|
LoRa.print(message);
|
||||||
|
LoRa.endPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
void readNFC()
|
||||||
|
{
|
||||||
|
if (nfc.tagPresent())
|
||||||
|
{
|
||||||
|
NfcTag tag = nfc.read();
|
||||||
|
tagId = tag.getUidString();
|
||||||
|
Serial.print("Tag ID: ");
|
||||||
|
Serial.println(tagId);
|
||||||
|
|
||||||
|
if (tag.hasNdefMessage())
|
||||||
|
{
|
||||||
|
NdefMessage message = tag.getNdefMessage();
|
||||||
|
int recordCount = message.getRecordCount();
|
||||||
|
Serial.print("Number of NDEF records: ");
|
||||||
|
Serial.println(recordCount);
|
||||||
|
|
||||||
|
for (int i = 0; i < recordCount; i++)
|
||||||
|
{
|
||||||
|
NdefRecord record = message.getRecord(i);
|
||||||
|
int payloadLength = record.getPayloadLength();
|
||||||
|
byte payload[payloadLength];
|
||||||
|
record.getPayload(payload);
|
||||||
|
|
||||||
|
String payloadAsString = "";
|
||||||
|
for (int c = 0; c < payloadLength; c++)
|
||||||
|
{
|
||||||
|
payloadAsString += (char)payload[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanString = payloadAsString;
|
||||||
|
cleanString.remove(0, 3);
|
||||||
|
Serial.print("Payload: ");
|
||||||
|
Serial.println(cleanString);
|
||||||
|
|
||||||
|
String uid = record.getId();
|
||||||
|
if (uid != "")
|
||||||
|
{
|
||||||
|
Serial.print("Record ID: ");
|
||||||
|
Serial.println(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serial.println("No NDEF message found on the tag.");
|
||||||
|
}
|
||||||
|
delay(2000);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,167 @@
|
|||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
/*
|
||||||
|
* arduinoLoRa Library just only support SX1276/Sx1278,Not support SX1262
|
||||||
|
* */
|
||||||
|
// #define LILYGO_TBeam_V0_7
|
||||||
|
#define LILYGO_TBeam_V1_0
|
||||||
|
// #define LILYGO_TBeam_V1_1
|
||||||
|
// #define LILYGO_T3_V1_0
|
||||||
|
// #define LILYGO_T3_V1_6
|
||||||
|
// #define LILYGO_T3_V2_0
|
||||||
|
// #define LILYGO_T95_V1_0
|
||||||
|
|
||||||
|
/*
|
||||||
|
* if you need to change it,
|
||||||
|
* please open this note and change to the frequency you need to test
|
||||||
|
* Option: 433E6,470E6,868E6,915E6
|
||||||
|
* */
|
||||||
|
|
||||||
|
#define LoRa_frequency 868E6
|
||||||
|
|
||||||
|
|
||||||
|
#define UNUSE_PIN (0)
|
||||||
|
|
||||||
|
#if defined(LILYGO_TBeam_V0_7)
|
||||||
|
#define GPS_RX_PIN 12
|
||||||
|
#define GPS_TX_PIN 15
|
||||||
|
#define BUTTON_PIN 39
|
||||||
|
#define BUTTON_PIN_MASK GPIO_SEL_39
|
||||||
|
#define I2C_SDA 21
|
||||||
|
#define I2C_SCL 22
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 5
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 27
|
||||||
|
#define RADIO_CS_PIN 18
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 23
|
||||||
|
#define RADIO_DIO1_PIN 33
|
||||||
|
#define RADIO_BUSY_PIN 32
|
||||||
|
|
||||||
|
#define BOARD_LED 14
|
||||||
|
#define LED_ON HIGH
|
||||||
|
#define LED_OFF LOW
|
||||||
|
|
||||||
|
#define GPS_BAUD_RATE 9600
|
||||||
|
#define HAS_GPS
|
||||||
|
#define HAS_DISPLAY //Optional, bring your own board, no OLED !!
|
||||||
|
|
||||||
|
#elif defined(LILYGO_TBeam_V1_0) || defined(LILYGO_TBeam_V1_1)
|
||||||
|
|
||||||
|
#define GPS_RX_PIN 34
|
||||||
|
#define GPS_TX_PIN 12
|
||||||
|
#define BUTTON_PIN 38
|
||||||
|
#define BUTTON_PIN_MASK GPIO_SEL_38
|
||||||
|
#define I2C_SDA 21
|
||||||
|
#define I2C_SCL 22
|
||||||
|
#define PMU_IRQ 35
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 5
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 27
|
||||||
|
#define RADIO_CS_PIN 18
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 23
|
||||||
|
#define RADIO_DIO1_PIN 33
|
||||||
|
#define RADIO_BUSY_PIN 32
|
||||||
|
|
||||||
|
#define BOARD_LED 4
|
||||||
|
#define LED_ON LOW
|
||||||
|
#define LED_OFF HIGH
|
||||||
|
|
||||||
|
#define GPS_BAUD_RATE 9600
|
||||||
|
#define HAS_GPS
|
||||||
|
#define HAS_DISPLAY //Optional, bring your own board, no OLED !!
|
||||||
|
|
||||||
|
#elif defined(LILYGO_T3_V1_0)
|
||||||
|
#define I2C_SDA 4
|
||||||
|
#define I2C_SCL 15
|
||||||
|
#define OLED_RST 16
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 5
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 27
|
||||||
|
#define RADIO_CS_PIN 18
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 14
|
||||||
|
#define RADIO_DIO1_PIN 33
|
||||||
|
#define RADIO_BUSY_PIN 32
|
||||||
|
|
||||||
|
#define HAS_DISPLAY
|
||||||
|
|
||||||
|
#elif defined(LILYGO_T3_V1_6)
|
||||||
|
#define I2C_SDA 21
|
||||||
|
#define I2C_SCL 22
|
||||||
|
#define OLED_RST UNUSE_PIN
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 5
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 27
|
||||||
|
#define RADIO_CS_PIN 18
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 23
|
||||||
|
#define RADIO_DIO1_PIN 33
|
||||||
|
#define RADIO_BUSY_PIN 32
|
||||||
|
|
||||||
|
#define SDCARD_MOSI 15
|
||||||
|
#define SDCARD_MISO 2
|
||||||
|
#define SDCARD_SCLK 14
|
||||||
|
#define SDCARD_CS 13
|
||||||
|
|
||||||
|
#define BOARD_LED 25
|
||||||
|
#define LED_ON HIGH
|
||||||
|
|
||||||
|
#define ADC_PIN 35
|
||||||
|
|
||||||
|
#define HAS_SDCARD
|
||||||
|
#define HAS_DISPLAY
|
||||||
|
|
||||||
|
#elif defined(LILYGO_T3_V2_0)
|
||||||
|
#define I2C_SDA 21
|
||||||
|
#define I2C_SCL 22
|
||||||
|
#define OLED_RST UNUSE_PIN
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 5
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 27
|
||||||
|
#define RADIO_CS_PIN 18
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 14
|
||||||
|
#define RADIO_DIO1_PIN UNUSE_PIN
|
||||||
|
#define RADIO_BUSY_PIN UNUSE_PIN
|
||||||
|
|
||||||
|
#define SDCARD_MOSI 15
|
||||||
|
#define SDCARD_MISO 2
|
||||||
|
#define SDCARD_SCLK 14
|
||||||
|
#define SDCARD_CS 13
|
||||||
|
|
||||||
|
#define BOARD_LED 0
|
||||||
|
#define LED_ON LOW
|
||||||
|
|
||||||
|
#define HAS_DISPLAY
|
||||||
|
#define HAS_SDCARD
|
||||||
|
|
||||||
|
#elif defined(LILYGO_T95_V1_0)
|
||||||
|
|
||||||
|
#define I2C_SDA 21
|
||||||
|
#define I2C_SCL 22
|
||||||
|
#define OLED_RST UNUSE_PIN
|
||||||
|
|
||||||
|
#define RADIO_SCLK_PIN 18
|
||||||
|
#define RADIO_MISO_PIN 19
|
||||||
|
#define RADIO_MOSI_PIN 23
|
||||||
|
#define RADIO_CS_PIN 5
|
||||||
|
#define RADIO_DI0_PIN 26
|
||||||
|
#define RADIO_RST_PIN 4
|
||||||
|
#define RADIO_DIO1_PIN 33
|
||||||
|
#define RADIO_DIO2_PIN 32
|
||||||
|
#define RADIO_BUSY_PIN UNUSE_PIN
|
||||||
|
|
||||||
|
#define ADC_PIN 35
|
||||||
|
#define HAS_DISPLAY
|
||||||
|
|
||||||
|
#else
|
||||||
|
#error "Please select the version you purchased in utilities.h"
|
||||||
|
#endif
|
@ -0,0 +1,99 @@
|
|||||||
|
#include <LoRa.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include "boards.h"
|
||||||
|
#include <PN532_I2C.h>
|
||||||
|
#include <PN532.h>
|
||||||
|
#include <NfcAdapter.h>
|
||||||
|
|
||||||
|
PN532_I2C pn532_i2c(Wire);
|
||||||
|
NfcAdapter nfc = NfcAdapter(pn532_i2c);
|
||||||
|
String tagId = "None";
|
||||||
|
String cleanString = "";
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
Serial.begin(9600);
|
||||||
|
Serial.println("System initialized");
|
||||||
|
nfc.begin();
|
||||||
|
|
||||||
|
initLoRa();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop()
|
||||||
|
{
|
||||||
|
readNFC();
|
||||||
|
if (!cleanString.isEmpty()) {
|
||||||
|
sendLoRaData(cleanString);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void initLoRa()
|
||||||
|
{
|
||||||
|
Serial.println("Initializing LoRa...");
|
||||||
|
LoRa.setPins(RADIO_CS_PIN, RADIO_RST_PIN, RADIO_DI0_PIN);
|
||||||
|
if (!LoRa.begin(LoRa_frequency))
|
||||||
|
{
|
||||||
|
Serial.println("Starting LoRa failed!");
|
||||||
|
while (1);
|
||||||
|
}
|
||||||
|
Serial.println("LoRa initialized successfully!");
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendLoRaData(String data)
|
||||||
|
{
|
||||||
|
Serial.print("Sending LoRa data: ");
|
||||||
|
Serial.println(data);
|
||||||
|
|
||||||
|
LoRa.beginPacket();
|
||||||
|
LoRa.print("3 " + data);
|
||||||
|
LoRa.endPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
void readNFC()
|
||||||
|
{
|
||||||
|
if (nfc.tagPresent())
|
||||||
|
{
|
||||||
|
NfcTag tag = nfc.read();
|
||||||
|
tagId = tag.getUidString();
|
||||||
|
Serial.print("Tag ID: ");
|
||||||
|
Serial.println(tagId);
|
||||||
|
|
||||||
|
if (tag.hasNdefMessage())
|
||||||
|
{
|
||||||
|
NdefMessage message = tag.getNdefMessage();
|
||||||
|
int recordCount = message.getRecordCount();
|
||||||
|
Serial.print("Number of NDEF records: ");
|
||||||
|
Serial.println(recordCount);
|
||||||
|
|
||||||
|
for (int i = 0; i < recordCount; i++)
|
||||||
|
{
|
||||||
|
NdefRecord record = message.getRecord(i);
|
||||||
|
int payloadLength = record.getPayloadLength();
|
||||||
|
byte payload[payloadLength];
|
||||||
|
record.getPayload(payload);
|
||||||
|
|
||||||
|
String payloadAsString = "";
|
||||||
|
for (int c = 0; c < payloadLength; c++)
|
||||||
|
{
|
||||||
|
payloadAsString += String((char)payload[c]);
|
||||||
|
}
|
||||||
|
cleanString = payloadAsString;
|
||||||
|
cleanString.remove(0, 3);
|
||||||
|
Serial.print("Payload: ");
|
||||||
|
Serial.println(cleanString);
|
||||||
|
|
||||||
|
String uid = record.getId();
|
||||||
|
if (uid != "")
|
||||||
|
{
|
||||||
|
Serial.print("Record ID: ");
|
||||||
|
Serial.println(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serial.println("No NDEF message found on the tag.");
|
||||||
|
}
|
||||||
|
delay(2000);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../color-support/bin.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../color-support/bin.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\color-support\bin.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../color-support/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../color-support/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../color-support/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../color-support/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../mime/cli.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../mime/cli.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../mime/cli.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../mkdirp/bin/cmd.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
exec "$basedir/../node/bin/node" "$@"
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../node-gyp/bin/node-gyp.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../node-gyp/bin/node-gyp.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../node-gyp-build/bin.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../node-gyp-build/bin.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../node-gyp-build/optional.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../node-gyp-build/optional.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\optional.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../node-gyp-build/optional.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../node-gyp-build/build-test.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../node-gyp-build/build-test.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\build-test.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\bin.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../node-gyp-build/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp\bin\node-gyp.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../which/bin/node-which" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../which/bin/node-which" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,9 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
"%dp0%\..\node\bin\node" %*
|
@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/../node/bin/node" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/../node/bin/node" $args
|
||||||
|
}
|
||||||
|
exit $LASTEXITCODE
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../nopt/bin/nopt.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../nopt/bin/nopt.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nopt\bin\nopt.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../nopt/bin/nopt.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../nopt/bin/nopt.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../rimraf/bin.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../rimraf/bin.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\rimraf\bin.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../rimraf/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../rimraf/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../rimraf/bin.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../rimraf/bin.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,14 @@
|
|||||||
|
Copyright (c) 2015, Contributors
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software
|
||||||
|
for any purpose with or without fee is hereby granted, provided
|
||||||
|
that the above copyright notice and this permission notice
|
||||||
|
appear in all copies.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||||
|
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
|
||||||
|
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
|
||||||
|
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||||
|
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||||
|
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||||
|
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
@ -0,0 +1,143 @@
|
|||||||
|
# @isaacs/cliui
|
||||||
|
|
||||||
|
Temporary fork of [cliui](http://npm.im/cliui).
|
||||||
|
|
||||||
|
![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg)
|
||||||
|
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
|
||||||
|
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
|
||||||
|
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui)
|
||||||
|
|
||||||
|
easily create complex multi-column command-line-interfaces.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
const ui = require('cliui')()
|
||||||
|
|
||||||
|
ui.div('Usage: $0 [command] [options]')
|
||||||
|
|
||||||
|
ui.div({
|
||||||
|
text: 'Options:',
|
||||||
|
padding: [2, 0, 1, 0]
|
||||||
|
})
|
||||||
|
|
||||||
|
ui.div(
|
||||||
|
{
|
||||||
|
text: "-f, --file",
|
||||||
|
width: 20,
|
||||||
|
padding: [0, 4, 0, 4]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: "the file to load." +
|
||||||
|
chalk.green("(if this description is long it wraps).")
|
||||||
|
,
|
||||||
|
width: 20
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: chalk.red("[required]"),
|
||||||
|
align: 'right'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
console.log(ui.toString())
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deno/ESM Support
|
||||||
|
|
||||||
|
As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and
|
||||||
|
[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import cliui from "https://deno.land/x/cliui/deno.ts";
|
||||||
|
|
||||||
|
const ui = cliui({})
|
||||||
|
|
||||||
|
ui.div('Usage: $0 [command] [options]')
|
||||||
|
|
||||||
|
ui.div({
|
||||||
|
text: 'Options:',
|
||||||
|
padding: [2, 0, 1, 0]
|
||||||
|
})
|
||||||
|
|
||||||
|
ui.div({
|
||||||
|
text: "-f, --file",
|
||||||
|
width: 20,
|
||||||
|
padding: [0, 4, 0, 4]
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log(ui.toString())
|
||||||
|
```
|
||||||
|
|
||||||
|
<img width="500" src="screenshot.png">
|
||||||
|
|
||||||
|
## Layout DSL
|
||||||
|
|
||||||
|
cliui exposes a simple layout DSL:
|
||||||
|
|
||||||
|
If you create a single `ui.div`, passing a string rather than an
|
||||||
|
object:
|
||||||
|
|
||||||
|
* `\n`: characters will be interpreted as new rows.
|
||||||
|
* `\t`: characters will be interpreted as new columns.
|
||||||
|
* `\s`: characters will be interpreted as padding.
|
||||||
|
|
||||||
|
**as an example...**
|
||||||
|
|
||||||
|
```js
|
||||||
|
var ui = require('./')({
|
||||||
|
width: 60
|
||||||
|
})
|
||||||
|
|
||||||
|
ui.div(
|
||||||
|
'Usage: node ./bin/foo.js\n' +
|
||||||
|
' <regex>\t provide a regex\n' +
|
||||||
|
' <glob>\t provide a glob\t [required]'
|
||||||
|
)
|
||||||
|
|
||||||
|
console.log(ui.toString())
|
||||||
|
```
|
||||||
|
|
||||||
|
**will output:**
|
||||||
|
|
||||||
|
```shell
|
||||||
|
Usage: node ./bin/foo.js
|
||||||
|
<regex> provide a regex
|
||||||
|
<glob> provide a glob [required]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
```js
|
||||||
|
cliui = require('cliui')
|
||||||
|
```
|
||||||
|
|
||||||
|
### cliui({width: integer})
|
||||||
|
|
||||||
|
Specify the maximum width of the UI being generated.
|
||||||
|
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.
|
||||||
|
|
||||||
|
### cliui({wrap: boolean})
|
||||||
|
|
||||||
|
Enable or disable the wrapping of text in a column.
|
||||||
|
|
||||||
|
### cliui.div(column, column, column)
|
||||||
|
|
||||||
|
Create a row with any number of columns, a column
|
||||||
|
can either be a string, or an object with the following
|
||||||
|
options:
|
||||||
|
|
||||||
|
* **text:** some text to place in the column.
|
||||||
|
* **width:** the width of a column.
|
||||||
|
* **align:** alignment, `right` or `center`.
|
||||||
|
* **padding:** `[top, right, bottom, left]`.
|
||||||
|
* **border:** should a border be placed around the div?
|
||||||
|
|
||||||
|
### cliui.span(column, column, column)
|
||||||
|
|
||||||
|
Similar to `div`, except the next row will be appended without
|
||||||
|
a new line being created.
|
||||||
|
|
||||||
|
### cliui.resetOutput()
|
||||||
|
|
||||||
|
Resets the UI elements of the current cliui instance, maintaining the values
|
||||||
|
set for `width` and `wrap`.
|
@ -0,0 +1,317 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const align = {
|
||||||
|
right: alignRight,
|
||||||
|
center: alignCenter
|
||||||
|
};
|
||||||
|
const top = 0;
|
||||||
|
const right = 1;
|
||||||
|
const bottom = 2;
|
||||||
|
const left = 3;
|
||||||
|
class UI {
|
||||||
|
constructor(opts) {
|
||||||
|
var _a;
|
||||||
|
this.width = opts.width;
|
||||||
|
/* c8 ignore start */
|
||||||
|
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
this.rows = [];
|
||||||
|
}
|
||||||
|
span(...args) {
|
||||||
|
const cols = this.div(...args);
|
||||||
|
cols.span = true;
|
||||||
|
}
|
||||||
|
resetOutput() {
|
||||||
|
this.rows = [];
|
||||||
|
}
|
||||||
|
div(...args) {
|
||||||
|
if (args.length === 0) {
|
||||||
|
this.div('');
|
||||||
|
}
|
||||||
|
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||||
|
return this.applyLayoutDSL(args[0]);
|
||||||
|
}
|
||||||
|
const cols = args.map(arg => {
|
||||||
|
if (typeof arg === 'string') {
|
||||||
|
return this.colFromString(arg);
|
||||||
|
}
|
||||||
|
return arg;
|
||||||
|
});
|
||||||
|
this.rows.push(cols);
|
||||||
|
return cols;
|
||||||
|
}
|
||||||
|
shouldApplyLayoutDSL(...args) {
|
||||||
|
return args.length === 1 && typeof args[0] === 'string' &&
|
||||||
|
/[\t\n]/.test(args[0]);
|
||||||
|
}
|
||||||
|
applyLayoutDSL(str) {
|
||||||
|
const rows = str.split('\n').map(row => row.split('\t'));
|
||||||
|
let leftColumnWidth = 0;
|
||||||
|
// simple heuristic for layout, make sure the
|
||||||
|
// second column lines up along the left-hand.
|
||||||
|
// don't allow the first column to take up more
|
||||||
|
// than 50% of the screen.
|
||||||
|
rows.forEach(columns => {
|
||||||
|
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||||
|
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// generate a table:
|
||||||
|
// replacing ' ' with padding calculations.
|
||||||
|
// using the algorithmically generated width.
|
||||||
|
rows.forEach(columns => {
|
||||||
|
this.div(...columns.map((r, i) => {
|
||||||
|
return {
|
||||||
|
text: r.trim(),
|
||||||
|
padding: this.measurePadding(r),
|
||||||
|
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
return this.rows[this.rows.length - 1];
|
||||||
|
}
|
||||||
|
colFromString(text) {
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
padding: this.measurePadding(text)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
measurePadding(str) {
|
||||||
|
// measure padding without ansi escape codes
|
||||||
|
const noAnsi = mixin.stripAnsi(str);
|
||||||
|
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
const lines = [];
|
||||||
|
this.rows.forEach(row => {
|
||||||
|
this.rowToString(row, lines);
|
||||||
|
});
|
||||||
|
// don't display any lines with the
|
||||||
|
// hidden flag set.
|
||||||
|
return lines
|
||||||
|
.filter(line => !line.hidden)
|
||||||
|
.map(line => line.text)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
rowToString(row, lines) {
|
||||||
|
this.rasterize(row).forEach((rrow, r) => {
|
||||||
|
let str = '';
|
||||||
|
rrow.forEach((col, c) => {
|
||||||
|
const { width } = row[c]; // the width with padding.
|
||||||
|
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||||
|
let ts = col; // temporary string used during alignment/padding.
|
||||||
|
if (wrapWidth > mixin.stringWidth(col)) {
|
||||||
|
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||||
|
}
|
||||||
|
// align the string within its column.
|
||||||
|
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||||
|
const fn = align[row[c].align];
|
||||||
|
ts = fn(ts, wrapWidth);
|
||||||
|
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||||
|
/* c8 ignore start */
|
||||||
|
const w = width || 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
ts += ' '.repeat(w - mixin.stringWidth(ts) - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// apply border and padding to string.
|
||||||
|
const padding = row[c].padding || [0, 0, 0, 0];
|
||||||
|
if (padding[left]) {
|
||||||
|
str += ' '.repeat(padding[left]);
|
||||||
|
}
|
||||||
|
str += addBorder(row[c], ts, '| ');
|
||||||
|
str += ts;
|
||||||
|
str += addBorder(row[c], ts, ' |');
|
||||||
|
if (padding[right]) {
|
||||||
|
str += ' '.repeat(padding[right]);
|
||||||
|
}
|
||||||
|
// if prior row is span, try to render the
|
||||||
|
// current row on the prior line.
|
||||||
|
if (r === 0 && lines.length > 0) {
|
||||||
|
str = this.renderInline(str, lines[lines.length - 1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// remove trailing whitespace.
|
||||||
|
lines.push({
|
||||||
|
text: str.replace(/ +$/, ''),
|
||||||
|
span: row.span
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
// if the full 'source' can render in
|
||||||
|
// the target line, do so.
|
||||||
|
renderInline(source, previousLine) {
|
||||||
|
const match = source.match(/^ */);
|
||||||
|
/* c8 ignore start */
|
||||||
|
const leadingWhitespace = match ? match[0].length : 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
const target = previousLine.text;
|
||||||
|
const targetTextWidth = mixin.stringWidth(target.trimEnd());
|
||||||
|
if (!previousLine.span) {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
// if we're not applying wrapping logic,
|
||||||
|
// just always append to the span.
|
||||||
|
if (!this.wrap) {
|
||||||
|
previousLine.hidden = true;
|
||||||
|
return target + source;
|
||||||
|
}
|
||||||
|
if (leadingWhitespace < targetTextWidth) {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
previousLine.hidden = true;
|
||||||
|
return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart();
|
||||||
|
}
|
||||||
|
rasterize(row) {
|
||||||
|
const rrows = [];
|
||||||
|
const widths = this.columnWidths(row);
|
||||||
|
let wrapped;
|
||||||
|
// word wrap all columns, and create
|
||||||
|
// a data-structure that is easy to rasterize.
|
||||||
|
row.forEach((col, c) => {
|
||||||
|
// leave room for left and right padding.
|
||||||
|
col.width = widths[c];
|
||||||
|
if (this.wrap) {
|
||||||
|
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
wrapped = col.text.split('\n');
|
||||||
|
}
|
||||||
|
if (col.border) {
|
||||||
|
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||||
|
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||||
|
}
|
||||||
|
// add top and bottom padding.
|
||||||
|
if (col.padding) {
|
||||||
|
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||||
|
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||||
|
}
|
||||||
|
wrapped.forEach((str, r) => {
|
||||||
|
if (!rrows[r]) {
|
||||||
|
rrows.push([]);
|
||||||
|
}
|
||||||
|
const rrow = rrows[r];
|
||||||
|
for (let i = 0; i < c; i++) {
|
||||||
|
if (rrow[i] === undefined) {
|
||||||
|
rrow.push('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rrow.push(str);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return rrows;
|
||||||
|
}
|
||||||
|
negatePadding(col) {
|
||||||
|
/* c8 ignore start */
|
||||||
|
let wrapWidth = col.width || 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
if (col.padding) {
|
||||||
|
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||||
|
}
|
||||||
|
if (col.border) {
|
||||||
|
wrapWidth -= 4;
|
||||||
|
}
|
||||||
|
return wrapWidth;
|
||||||
|
}
|
||||||
|
columnWidths(row) {
|
||||||
|
if (!this.wrap) {
|
||||||
|
return row.map(col => {
|
||||||
|
return col.width || mixin.stringWidth(col.text);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let unset = row.length;
|
||||||
|
let remainingWidth = this.width;
|
||||||
|
// column widths can be set in config.
|
||||||
|
const widths = row.map(col => {
|
||||||
|
if (col.width) {
|
||||||
|
unset--;
|
||||||
|
remainingWidth -= col.width;
|
||||||
|
return col.width;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
// any unset widths should be calculated.
|
||||||
|
/* c8 ignore start */
|
||||||
|
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
return widths.map((w, i) => {
|
||||||
|
if (w === undefined) {
|
||||||
|
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function addBorder(col, ts, style) {
|
||||||
|
if (col.border) {
|
||||||
|
if (/[.']-+[.']/.test(ts)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
if (ts.trim().length !== 0) {
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
return ' ';
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
// calculates the minimum width of
|
||||||
|
// a column, based on padding preferences.
|
||||||
|
function _minWidth(col) {
|
||||||
|
const padding = col.padding || [];
|
||||||
|
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||||
|
if (col.border) {
|
||||||
|
return minWidth + 4;
|
||||||
|
}
|
||||||
|
return minWidth;
|
||||||
|
}
|
||||||
|
function getWindowWidth() {
|
||||||
|
/* c8 ignore start */
|
||||||
|
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||||
|
return process.stdout.columns;
|
||||||
|
}
|
||||||
|
return 80;
|
||||||
|
}
|
||||||
|
/* c8 ignore stop */
|
||||||
|
function alignRight(str, width) {
|
||||||
|
str = str.trim();
|
||||||
|
const strWidth = mixin.stringWidth(str);
|
||||||
|
if (strWidth < width) {
|
||||||
|
return ' '.repeat(width - strWidth) + str;
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
function alignCenter(str, width) {
|
||||||
|
str = str.trim();
|
||||||
|
const strWidth = mixin.stringWidth(str);
|
||||||
|
/* c8 ignore start */
|
||||||
|
if (strWidth >= width) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
/* c8 ignore stop */
|
||||||
|
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||||
|
}
|
||||||
|
let mixin;
|
||||||
|
function cliui(opts, _mixin) {
|
||||||
|
mixin = _mixin;
|
||||||
|
return new UI({
|
||||||
|
/* c8 ignore start */
|
||||||
|
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||||
|
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||||
|
/* c8 ignore stop */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bootstrap cliui with CommonJS dependencies:
|
||||||
|
const stringWidth = require('string-width-cjs');
|
||||||
|
const stripAnsi = require('strip-ansi-cjs');
|
||||||
|
const wrap = require('wrap-ansi-cjs');
|
||||||
|
function ui(opts) {
|
||||||
|
return cliui(opts, {
|
||||||
|
stringWidth,
|
||||||
|
stripAnsi,
|
||||||
|
wrap
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ui;
|
@ -0,0 +1,43 @@
|
|||||||
|
interface UIOptions {
|
||||||
|
width: number;
|
||||||
|
wrap?: boolean;
|
||||||
|
rows?: string[];
|
||||||
|
}
|
||||||
|
interface Column {
|
||||||
|
text: string;
|
||||||
|
width?: number;
|
||||||
|
align?: "right" | "left" | "center";
|
||||||
|
padding: number[];
|
||||||
|
border?: boolean;
|
||||||
|
}
|
||||||
|
interface ColumnArray extends Array<Column> {
|
||||||
|
span: boolean;
|
||||||
|
}
|
||||||
|
interface Line {
|
||||||
|
hidden?: boolean;
|
||||||
|
text: string;
|
||||||
|
span?: boolean;
|
||||||
|
}
|
||||||
|
declare class UI {
|
||||||
|
width: number;
|
||||||
|
wrap: boolean;
|
||||||
|
rows: ColumnArray[];
|
||||||
|
constructor(opts: UIOptions);
|
||||||
|
span(...args: ColumnArray): void;
|
||||||
|
resetOutput(): void;
|
||||||
|
div(...args: (Column | string)[]): ColumnArray;
|
||||||
|
private shouldApplyLayoutDSL;
|
||||||
|
private applyLayoutDSL;
|
||||||
|
private colFromString;
|
||||||
|
private measurePadding;
|
||||||
|
toString(): string;
|
||||||
|
rowToString(row: ColumnArray, lines: Line[]): Line[];
|
||||||
|
// if the full 'source' can render in
|
||||||
|
// the target line, do so.
|
||||||
|
private renderInline;
|
||||||
|
private rasterize;
|
||||||
|
private negatePadding;
|
||||||
|
private columnWidths;
|
||||||
|
}
|
||||||
|
declare function ui(opts: UIOptions): UI;
|
||||||
|
export { ui as default };
|
@ -0,0 +1,302 @@
|
|||||||
|
'use strict';
|
||||||
|
const align = {
|
||||||
|
right: alignRight,
|
||||||
|
center: alignCenter
|
||||||
|
};
|
||||||
|
const top = 0;
|
||||||
|
const right = 1;
|
||||||
|
const bottom = 2;
|
||||||
|
const left = 3;
|
||||||
|
export class UI {
|
||||||
|
constructor(opts) {
|
||||||
|
var _a;
|
||||||
|
this.width = opts.width;
|
||||||
|
/* c8 ignore start */
|
||||||
|
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
this.rows = [];
|
||||||
|
}
|
||||||
|
span(...args) {
|
||||||
|
const cols = this.div(...args);
|
||||||
|
cols.span = true;
|
||||||
|
}
|
||||||
|
resetOutput() {
|
||||||
|
this.rows = [];
|
||||||
|
}
|
||||||
|
div(...args) {
|
||||||
|
if (args.length === 0) {
|
||||||
|
this.div('');
|
||||||
|
}
|
||||||
|
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||||
|
return this.applyLayoutDSL(args[0]);
|
||||||
|
}
|
||||||
|
const cols = args.map(arg => {
|
||||||
|
if (typeof arg === 'string') {
|
||||||
|
return this.colFromString(arg);
|
||||||
|
}
|
||||||
|
return arg;
|
||||||
|
});
|
||||||
|
this.rows.push(cols);
|
||||||
|
return cols;
|
||||||
|
}
|
||||||
|
shouldApplyLayoutDSL(...args) {
|
||||||
|
return args.length === 1 && typeof args[0] === 'string' &&
|
||||||
|
/[\t\n]/.test(args[0]);
|
||||||
|
}
|
||||||
|
applyLayoutDSL(str) {
|
||||||
|
const rows = str.split('\n').map(row => row.split('\t'));
|
||||||
|
let leftColumnWidth = 0;
|
||||||
|
// simple heuristic for layout, make sure the
|
||||||
|
// second column lines up along the left-hand.
|
||||||
|
// don't allow the first column to take up more
|
||||||
|
// than 50% of the screen.
|
||||||
|
rows.forEach(columns => {
|
||||||
|
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||||
|
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// generate a table:
|
||||||
|
// replacing ' ' with padding calculations.
|
||||||
|
// using the algorithmically generated width.
|
||||||
|
rows.forEach(columns => {
|
||||||
|
this.div(...columns.map((r, i) => {
|
||||||
|
return {
|
||||||
|
text: r.trim(),
|
||||||
|
padding: this.measurePadding(r),
|
||||||
|
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
return this.rows[this.rows.length - 1];
|
||||||
|
}
|
||||||
|
colFromString(text) {
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
padding: this.measurePadding(text)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
measurePadding(str) {
|
||||||
|
// measure padding without ansi escape codes
|
||||||
|
const noAnsi = mixin.stripAnsi(str);
|
||||||
|
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
const lines = [];
|
||||||
|
this.rows.forEach(row => {
|
||||||
|
this.rowToString(row, lines);
|
||||||
|
});
|
||||||
|
// don't display any lines with the
|
||||||
|
// hidden flag set.
|
||||||
|
return lines
|
||||||
|
.filter(line => !line.hidden)
|
||||||
|
.map(line => line.text)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
rowToString(row, lines) {
|
||||||
|
this.rasterize(row).forEach((rrow, r) => {
|
||||||
|
let str = '';
|
||||||
|
rrow.forEach((col, c) => {
|
||||||
|
const { width } = row[c]; // the width with padding.
|
||||||
|
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||||
|
let ts = col; // temporary string used during alignment/padding.
|
||||||
|
if (wrapWidth > mixin.stringWidth(col)) {
|
||||||
|
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||||
|
}
|
||||||
|
// align the string within its column.
|
||||||
|
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||||
|
const fn = align[row[c].align];
|
||||||
|
ts = fn(ts, wrapWidth);
|
||||||
|
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||||
|
/* c8 ignore start */
|
||||||
|
const w = width || 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
ts += ' '.repeat(w - mixin.stringWidth(ts) - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// apply border and padding to string.
|
||||||
|
const padding = row[c].padding || [0, 0, 0, 0];
|
||||||
|
if (padding[left]) {
|
||||||
|
str += ' '.repeat(padding[left]);
|
||||||
|
}
|
||||||
|
str += addBorder(row[c], ts, '| ');
|
||||||
|
str += ts;
|
||||||
|
str += addBorder(row[c], ts, ' |');
|
||||||
|
if (padding[right]) {
|
||||||
|
str += ' '.repeat(padding[right]);
|
||||||
|
}
|
||||||
|
// if prior row is span, try to render the
|
||||||
|
// current row on the prior line.
|
||||||
|
if (r === 0 && lines.length > 0) {
|
||||||
|
str = this.renderInline(str, lines[lines.length - 1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// remove trailing whitespace.
|
||||||
|
lines.push({
|
||||||
|
text: str.replace(/ +$/, ''),
|
||||||
|
span: row.span
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
// if the full 'source' can render in
|
||||||
|
// the target line, do so.
|
||||||
|
renderInline(source, previousLine) {
|
||||||
|
const match = source.match(/^ */);
|
||||||
|
/* c8 ignore start */
|
||||||
|
const leadingWhitespace = match ? match[0].length : 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
const target = previousLine.text;
|
||||||
|
const targetTextWidth = mixin.stringWidth(target.trimEnd());
|
||||||
|
if (!previousLine.span) {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
// if we're not applying wrapping logic,
|
||||||
|
// just always append to the span.
|
||||||
|
if (!this.wrap) {
|
||||||
|
previousLine.hidden = true;
|
||||||
|
return target + source;
|
||||||
|
}
|
||||||
|
if (leadingWhitespace < targetTextWidth) {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
previousLine.hidden = true;
|
||||||
|
return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart();
|
||||||
|
}
|
||||||
|
rasterize(row) {
|
||||||
|
const rrows = [];
|
||||||
|
const widths = this.columnWidths(row);
|
||||||
|
let wrapped;
|
||||||
|
// word wrap all columns, and create
|
||||||
|
// a data-structure that is easy to rasterize.
|
||||||
|
row.forEach((col, c) => {
|
||||||
|
// leave room for left and right padding.
|
||||||
|
col.width = widths[c];
|
||||||
|
if (this.wrap) {
|
||||||
|
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
wrapped = col.text.split('\n');
|
||||||
|
}
|
||||||
|
if (col.border) {
|
||||||
|
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||||
|
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||||
|
}
|
||||||
|
// add top and bottom padding.
|
||||||
|
if (col.padding) {
|
||||||
|
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||||
|
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||||
|
}
|
||||||
|
wrapped.forEach((str, r) => {
|
||||||
|
if (!rrows[r]) {
|
||||||
|
rrows.push([]);
|
||||||
|
}
|
||||||
|
const rrow = rrows[r];
|
||||||
|
for (let i = 0; i < c; i++) {
|
||||||
|
if (rrow[i] === undefined) {
|
||||||
|
rrow.push('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rrow.push(str);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return rrows;
|
||||||
|
}
|
||||||
|
negatePadding(col) {
|
||||||
|
/* c8 ignore start */
|
||||||
|
let wrapWidth = col.width || 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
if (col.padding) {
|
||||||
|
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||||
|
}
|
||||||
|
if (col.border) {
|
||||||
|
wrapWidth -= 4;
|
||||||
|
}
|
||||||
|
return wrapWidth;
|
||||||
|
}
|
||||||
|
columnWidths(row) {
|
||||||
|
if (!this.wrap) {
|
||||||
|
return row.map(col => {
|
||||||
|
return col.width || mixin.stringWidth(col.text);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let unset = row.length;
|
||||||
|
let remainingWidth = this.width;
|
||||||
|
// column widths can be set in config.
|
||||||
|
const widths = row.map(col => {
|
||||||
|
if (col.width) {
|
||||||
|
unset--;
|
||||||
|
remainingWidth -= col.width;
|
||||||
|
return col.width;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
// any unset widths should be calculated.
|
||||||
|
/* c8 ignore start */
|
||||||
|
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||||
|
/* c8 ignore stop */
|
||||||
|
return widths.map((w, i) => {
|
||||||
|
if (w === undefined) {
|
||||||
|
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function addBorder(col, ts, style) {
|
||||||
|
if (col.border) {
|
||||||
|
if (/[.']-+[.']/.test(ts)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
if (ts.trim().length !== 0) {
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
return ' ';
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
// calculates the minimum width of
|
||||||
|
// a column, based on padding preferences.
|
||||||
|
function _minWidth(col) {
|
||||||
|
const padding = col.padding || [];
|
||||||
|
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||||
|
if (col.border) {
|
||||||
|
return minWidth + 4;
|
||||||
|
}
|
||||||
|
return minWidth;
|
||||||
|
}
|
||||||
|
function getWindowWidth() {
|
||||||
|
/* c8 ignore start */
|
||||||
|
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||||
|
return process.stdout.columns;
|
||||||
|
}
|
||||||
|
return 80;
|
||||||
|
}
|
||||||
|
/* c8 ignore stop */
|
||||||
|
function alignRight(str, width) {
|
||||||
|
str = str.trim();
|
||||||
|
const strWidth = mixin.stringWidth(str);
|
||||||
|
if (strWidth < width) {
|
||||||
|
return ' '.repeat(width - strWidth) + str;
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
function alignCenter(str, width) {
|
||||||
|
str = str.trim();
|
||||||
|
const strWidth = mixin.stringWidth(str);
|
||||||
|
/* c8 ignore start */
|
||||||
|
if (strWidth >= width) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
/* c8 ignore stop */
|
||||||
|
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||||
|
}
|
||||||
|
let mixin;
|
||||||
|
export function cliui(opts, _mixin) {
|
||||||
|
mixin = _mixin;
|
||||||
|
return new UI({
|
||||||
|
/* c8 ignore start */
|
||||||
|
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||||
|
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||||
|
/* c8 ignore stop */
|
||||||
|
});
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
// Bootstrap cliui with ESM dependencies:
|
||||||
|
import { cliui } from './build/lib/index.js'
|
||||||
|
|
||||||
|
import stringWidth from 'string-width'
|
||||||
|
import stripAnsi from 'strip-ansi'
|
||||||
|
import wrap from 'wrap-ansi'
|
||||||
|
|
||||||
|
export default function ui (opts) {
|
||||||
|
return cliui(opts, {
|
||||||
|
stringWidth,
|
||||||
|
stripAnsi,
|
||||||
|
wrap
|
||||||
|
})
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
export interface Options {
|
||||||
|
/**
|
||||||
|
Match only the first ANSI escape.
|
||||||
|
|
||||||
|
@default false
|
||||||
|
*/
|
||||||
|
readonly onlyFirst: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
Regular expression for matching ANSI escape codes.
|
||||||
|
|
||||||
|
@example
|
||||||
|
```
|
||||||
|
import ansiRegex from 'ansi-regex';
|
||||||
|
|
||||||
|
ansiRegex().test('\u001B[4mcake\u001B[0m');
|
||||||
|
//=> true
|
||||||
|
|
||||||
|
ansiRegex().test('cake');
|
||||||
|
//=> false
|
||||||
|
|
||||||
|
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
|
||||||
|
//=> ['\u001B[4m', '\u001B[0m']
|
||||||
|
|
||||||
|
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
|
||||||
|
//=> ['\u001B[4m']
|
||||||
|
|
||||||
|
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
|
||||||
|
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
|
||||||
|
```
|
||||||
|
*/
|
||||||
|
export default function ansiRegex(options?: Options): RegExp;
|
@ -0,0 +1,8 @@
|
|||||||
|
export default function ansiRegex({onlyFirst = false} = {}) {
|
||||||
|
const pattern = [
|
||||||
|
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
|
||||||
|
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
|
||||||
|
].join('|');
|
||||||
|
|
||||||
|
return new RegExp(pattern, onlyFirst ? undefined : 'g');
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,58 @@
|
|||||||
|
{
|
||||||
|
"name": "ansi-regex",
|
||||||
|
"version": "6.0.1",
|
||||||
|
"description": "Regular expression for matching ANSI escape codes",
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": "chalk/ansi-regex",
|
||||||
|
"funding": "https://github.com/chalk/ansi-regex?sponsor=1",
|
||||||
|
"author": {
|
||||||
|
"name": "Sindre Sorhus",
|
||||||
|
"email": "sindresorhus@gmail.com",
|
||||||
|
"url": "https://sindresorhus.com"
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"exports": "./index.js",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "xo && ava && tsd",
|
||||||
|
"view-supported": "node fixtures/view-codes.js"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"index.js",
|
||||||
|
"index.d.ts"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"ansi",
|
||||||
|
"styles",
|
||||||
|
"color",
|
||||||
|
"colour",
|
||||||
|
"colors",
|
||||||
|
"terminal",
|
||||||
|
"console",
|
||||||
|
"cli",
|
||||||
|
"string",
|
||||||
|
"tty",
|
||||||
|
"escape",
|
||||||
|
"formatting",
|
||||||
|
"rgb",
|
||||||
|
"256",
|
||||||
|
"shell",
|
||||||
|
"xterm",
|
||||||
|
"command-line",
|
||||||
|
"text",
|
||||||
|
"regex",
|
||||||
|
"regexp",
|
||||||
|
"re",
|
||||||
|
"match",
|
||||||
|
"test",
|
||||||
|
"find",
|
||||||
|
"pattern"
|
||||||
|
],
|
||||||
|
"devDependencies": {
|
||||||
|
"ava": "^3.15.0",
|
||||||
|
"tsd": "^0.14.0",
|
||||||
|
"xo": "^0.38.2"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,72 @@
|
|||||||
|
# ansi-regex
|
||||||
|
|
||||||
|
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install ansi-regex
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```js
|
||||||
|
import ansiRegex from 'ansi-regex';
|
||||||
|
|
||||||
|
ansiRegex().test('\u001B[4mcake\u001B[0m');
|
||||||
|
//=> true
|
||||||
|
|
||||||
|
ansiRegex().test('cake');
|
||||||
|
//=> false
|
||||||
|
|
||||||
|
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
|
||||||
|
//=> ['\u001B[4m', '\u001B[0m']
|
||||||
|
|
||||||
|
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
|
||||||
|
//=> ['\u001B[4m']
|
||||||
|
|
||||||
|
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
|
||||||
|
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
### ansiRegex(options?)
|
||||||
|
|
||||||
|
Returns a regex for matching ANSI escape codes.
|
||||||
|
|
||||||
|
#### options
|
||||||
|
|
||||||
|
Type: `object`
|
||||||
|
|
||||||
|
##### onlyFirst
|
||||||
|
|
||||||
|
Type: `boolean`\
|
||||||
|
Default: `false` *(Matches any ANSI escape codes in a string)*
|
||||||
|
|
||||||
|
Match only the first ANSI escape.
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
### Why do you test for codes not in the ECMA 48 standard?
|
||||||
|
|
||||||
|
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
|
||||||
|
|
||||||
|
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
|
||||||
|
|
||||||
|
## Maintainers
|
||||||
|
|
||||||
|
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||||
|
- [Josh Junon](https://github.com/qix-)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<b>
|
||||||
|
<a href="https://tidelift.com/subscription/pkg/npm-ansi-regex?utm_source=npm-ansi-regex&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
|
||||||
|
</b>
|
||||||
|
<br>
|
||||||
|
<sub>
|
||||||
|
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
|
||||||
|
</sub>
|
||||||
|
</div>
|
@ -0,0 +1,29 @@
|
|||||||
|
export interface Options {
|
||||||
|
/**
|
||||||
|
Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2).
|
||||||
|
|
||||||
|
@default true
|
||||||
|
*/
|
||||||
|
readonly ambiguousIsNarrow: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
Get the visual width of a string - the number of columns required to display it.
|
||||||
|
|
||||||
|
Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width.
|
||||||
|
|
||||||
|
@example
|
||||||
|
```
|
||||||
|
import stringWidth from 'string-width';
|
||||||
|
|
||||||
|
stringWidth('a');
|
||||||
|
//=> 1
|
||||||
|
|
||||||
|
stringWidth('古');
|
||||||
|
//=> 2
|
||||||
|
|
||||||
|
stringWidth('\u001B[1m古\u001B[22m');
|
||||||
|
//=> 2
|
||||||
|
```
|
||||||
|
*/
|
||||||
|
export default function stringWidth(string: string, options?: Options): number;
|
@ -0,0 +1,54 @@
|
|||||||
|
import stripAnsi from 'strip-ansi';
|
||||||
|
import eastAsianWidth from 'eastasianwidth';
|
||||||
|
import emojiRegex from 'emoji-regex';
|
||||||
|
|
||||||
|
export default function stringWidth(string, options = {}) {
|
||||||
|
if (typeof string !== 'string' || string.length === 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
options = {
|
||||||
|
ambiguousIsNarrow: true,
|
||||||
|
...options
|
||||||
|
};
|
||||||
|
|
||||||
|
string = stripAnsi(string);
|
||||||
|
|
||||||
|
if (string.length === 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
string = string.replace(emojiRegex(), ' ');
|
||||||
|
|
||||||
|
const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
|
||||||
|
let width = 0;
|
||||||
|
|
||||||
|
for (const character of string) {
|
||||||
|
const codePoint = character.codePointAt(0);
|
||||||
|
|
||||||
|
// Ignore control characters
|
||||||
|
if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore combining characters
|
||||||
|
if (codePoint >= 0x300 && codePoint <= 0x36F) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = eastAsianWidth.eastAsianWidth(character);
|
||||||
|
switch (code) {
|
||||||
|
case 'F':
|
||||||
|
case 'W':
|
||||||
|
width += 2;
|
||||||
|
break;
|
||||||
|
case 'A':
|
||||||
|
width += ambiguousCharacterWidth;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
width += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return width;
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,59 @@
|
|||||||
|
{
|
||||||
|
"name": "string-width",
|
||||||
|
"version": "5.1.2",
|
||||||
|
"description": "Get the visual width of a string - the number of columns required to display it",
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": "sindresorhus/string-width",
|
||||||
|
"funding": "https://github.com/sponsors/sindresorhus",
|
||||||
|
"author": {
|
||||||
|
"name": "Sindre Sorhus",
|
||||||
|
"email": "sindresorhus@gmail.com",
|
||||||
|
"url": "https://sindresorhus.com"
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"exports": "./index.js",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "xo && ava && tsd"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"index.js",
|
||||||
|
"index.d.ts"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"string",
|
||||||
|
"character",
|
||||||
|
"unicode",
|
||||||
|
"width",
|
||||||
|
"visual",
|
||||||
|
"column",
|
||||||
|
"columns",
|
||||||
|
"fullwidth",
|
||||||
|
"full-width",
|
||||||
|
"full",
|
||||||
|
"ansi",
|
||||||
|
"escape",
|
||||||
|
"codes",
|
||||||
|
"cli",
|
||||||
|
"command-line",
|
||||||
|
"terminal",
|
||||||
|
"console",
|
||||||
|
"cjk",
|
||||||
|
"chinese",
|
||||||
|
"japanese",
|
||||||
|
"korean",
|
||||||
|
"fixed-width"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"eastasianwidth": "^0.2.0",
|
||||||
|
"emoji-regex": "^9.2.2",
|
||||||
|
"strip-ansi": "^7.0.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"ava": "^3.15.0",
|
||||||
|
"tsd": "^0.14.0",
|
||||||
|
"xo": "^0.38.2"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
# string-width
|
||||||
|
|
||||||
|
> Get the visual width of a string - the number of columns required to display it
|
||||||
|
|
||||||
|
Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width.
|
||||||
|
|
||||||
|
Useful to be able to measure the actual width of command-line output.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install string-width
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```js
|
||||||
|
import stringWidth from 'string-width';
|
||||||
|
|
||||||
|
stringWidth('a');
|
||||||
|
//=> 1
|
||||||
|
|
||||||
|
stringWidth('古');
|
||||||
|
//=> 2
|
||||||
|
|
||||||
|
stringWidth('\u001B[1m古\u001B[22m');
|
||||||
|
//=> 2
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
### stringWidth(string, options?)
|
||||||
|
|
||||||
|
#### string
|
||||||
|
|
||||||
|
Type: `string`
|
||||||
|
|
||||||
|
The string to be counted.
|
||||||
|
|
||||||
|
#### options
|
||||||
|
|
||||||
|
Type: `object`
|
||||||
|
|
||||||
|
##### ambiguousIsNarrow
|
||||||
|
|
||||||
|
Type: `boolean`\
|
||||||
|
Default: `false`
|
||||||
|
|
||||||
|
Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2).
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module
|
||||||
|
- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string
|
||||||
|
- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<b>
|
||||||
|
<a href="https://tidelift.com/subscription/pkg/npm-string-width?utm_source=npm-string-width&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
|
||||||
|
</b>
|
||||||
|
<br>
|
||||||
|
<sub>
|
||||||
|
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
|
||||||
|
</sub>
|
||||||
|
</div>
|
@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string.
|
||||||
|
|
||||||
|
@example
|
||||||
|
```
|
||||||
|
import stripAnsi from 'strip-ansi';
|
||||||
|
|
||||||
|
stripAnsi('\u001B[4mUnicorn\u001B[0m');
|
||||||
|
//=> 'Unicorn'
|
||||||
|
|
||||||
|
stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007');
|
||||||
|
//=> 'Click'
|
||||||
|
```
|
||||||
|
*/
|
||||||
|
export default function stripAnsi(string: string): string;
|
@ -0,0 +1,14 @@
|
|||||||
|
import ansiRegex from 'ansi-regex';
|
||||||
|
|
||||||
|
const regex = ansiRegex();
|
||||||
|
|
||||||
|
export default function stripAnsi(string) {
|
||||||
|
if (typeof string !== 'string') {
|
||||||
|
throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Even though the regex is global, we don't need to reset the `.lastIndex`
|
||||||
|
// because unlike `.exec()` and `.test()`, `.replace()` does it automatically
|
||||||
|
// and doing it manually has a performance penalty.
|
||||||
|
return string.replace(regex, '');
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"name": "strip-ansi",
|
||||||
|
"version": "7.1.0",
|
||||||
|
"description": "Strip ANSI escape codes from a string",
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": "chalk/strip-ansi",
|
||||||
|
"funding": "https://github.com/chalk/strip-ansi?sponsor=1",
|
||||||
|
"author": {
|
||||||
|
"name": "Sindre Sorhus",
|
||||||
|
"email": "sindresorhus@gmail.com",
|
||||||
|
"url": "https://sindresorhus.com"
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"exports": "./index.js",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "xo && ava && tsd"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"index.js",
|
||||||
|
"index.d.ts"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"strip",
|
||||||
|
"trim",
|
||||||
|
"remove",
|
||||||
|
"ansi",
|
||||||
|
"styles",
|
||||||
|
"color",
|
||||||
|
"colour",
|
||||||
|
"colors",
|
||||||
|
"terminal",
|
||||||
|
"console",
|
||||||
|
"string",
|
||||||
|
"tty",
|
||||||
|
"escape",
|
||||||
|
"formatting",
|
||||||
|
"rgb",
|
||||||
|
"256",
|
||||||
|
"shell",
|
||||||
|
"xterm",
|
||||||
|
"log",
|
||||||
|
"logging",
|
||||||
|
"command-line",
|
||||||
|
"text"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^6.0.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"ava": "^3.15.0",
|
||||||
|
"tsd": "^0.17.0",
|
||||||
|
"xo": "^0.44.0"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
# strip-ansi
|
||||||
|
|
||||||
|
> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install strip-ansi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```js
|
||||||
|
import stripAnsi from 'strip-ansi';
|
||||||
|
|
||||||
|
stripAnsi('\u001B[4mUnicorn\u001B[0m');
|
||||||
|
//=> 'Unicorn'
|
||||||
|
|
||||||
|
stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007');
|
||||||
|
//=> 'Click'
|
||||||
|
```
|
||||||
|
|
||||||
|
## strip-ansi for enterprise
|
||||||
|
|
||||||
|
Available as part of the Tidelift Subscription.
|
||||||
|
|
||||||
|
The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
|
||||||
|
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module
|
||||||
|
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
|
||||||
|
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
|
||||||
|
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
|
||||||
|
|
||||||
|
## Maintainers
|
||||||
|
|
||||||
|
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||||
|
- [Josh Junon](https://github.com/qix-)
|
||||||
|
|
@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"name": "@isaacs/cliui",
|
||||||
|
"version": "8.0.2",
|
||||||
|
"description": "easily create complex multi-column command-line-interfaces",
|
||||||
|
"main": "build/index.cjs",
|
||||||
|
"exports": {
|
||||||
|
".": [
|
||||||
|
{
|
||||||
|
"import": "./index.mjs",
|
||||||
|
"require": "./build/index.cjs"
|
||||||
|
},
|
||||||
|
"./build/index.cjs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"module": "./index.mjs",
|
||||||
|
"scripts": {
|
||||||
|
"check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'",
|
||||||
|
"fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'",
|
||||||
|
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
|
||||||
|
"test": "c8 mocha ./test/*.cjs",
|
||||||
|
"test:esm": "c8 mocha ./test/**/*.mjs",
|
||||||
|
"postest": "check",
|
||||||
|
"coverage": "c8 report --check-coverage",
|
||||||
|
"precompile": "rimraf build",
|
||||||
|
"compile": "tsc",
|
||||||
|
"postcompile": "npm run build:cjs",
|
||||||
|
"build:cjs": "rollup -c",
|
||||||
|
"prepare": "npm run compile"
|
||||||
|
},
|
||||||
|
"repository": "yargs/cliui",
|
||||||
|
"standard": {
|
||||||
|
"ignore": [
|
||||||
|
"**/example/**"
|
||||||
|
],
|
||||||
|
"globals": [
|
||||||
|
"it"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"keywords": [
|
||||||
|
"cli",
|
||||||
|
"command-line",
|
||||||
|
"layout",
|
||||||
|
"design",
|
||||||
|
"console",
|
||||||
|
"wrap",
|
||||||
|
"table"
|
||||||
|
],
|
||||||
|
"author": "Ben Coe <ben@npmjs.com>",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"string-width": "^5.1.2",
|
||||||
|
"string-width-cjs": "npm:string-width@^4.2.0",
|
||||||
|
"strip-ansi": "^7.0.1",
|
||||||
|
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
|
||||||
|
"wrap-ansi": "^8.1.0",
|
||||||
|
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^14.0.27",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^4.0.0",
|
||||||
|
"@typescript-eslint/parser": "^4.0.0",
|
||||||
|
"c8": "^7.3.0",
|
||||||
|
"chai": "^4.2.0",
|
||||||
|
"chalk": "^4.1.0",
|
||||||
|
"cross-env": "^7.0.2",
|
||||||
|
"eslint": "^7.6.0",
|
||||||
|
"eslint-plugin-import": "^2.22.0",
|
||||||
|
"eslint-plugin-node": "^11.1.0",
|
||||||
|
"gts": "^3.0.0",
|
||||||
|
"mocha": "^10.0.0",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"rollup": "^2.23.1",
|
||||||
|
"rollup-plugin-ts": "^3.0.2",
|
||||||
|
"standardx": "^7.0.0",
|
||||||
|
"typescript": "^4.0.0"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"build",
|
||||||
|
"index.mjs",
|
||||||
|
"!*.d.ts"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
<!-- This file is automatically added by @npmcli/template-oss. Do not edit. -->
|
||||||
|
|
||||||
|
ISC License
|
||||||
|
|
||||||
|
Copyright npm, Inc.
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this
|
||||||
|
software for any purpose with or without fee is hereby
|
||||||
|
granted, provided that the above copyright notice and this
|
||||||
|
permission notice appear in all copies.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL
|
||||||
|
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
|
||||||
|
EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||||
|
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||||
|
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
|
||||||
|
USE OR PERFORMANCE OF THIS SOFTWARE.
|
@ -0,0 +1,97 @@
|
|||||||
|
# @npmcli/fs
|
||||||
|
|
||||||
|
polyfills, and extensions, of the core `fs` module.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- `fs.cp` polyfill for node < 16.7.0
|
||||||
|
- `fs.withTempDir` added
|
||||||
|
- `fs.readdirScoped` added
|
||||||
|
- `fs.moveFile` added
|
||||||
|
|
||||||
|
## `fs.withTempDir(root, fn, options) -> Promise`
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
|
||||||
|
- `root`: the directory in which to create the temporary directory
|
||||||
|
- `fn`: a function that will be called with the path to the temporary directory
|
||||||
|
- `options`
|
||||||
|
- `tmpPrefix`: a prefix to be used in the generated directory name
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
The `withTempDir` function creates a temporary directory, runs the provided
|
||||||
|
function (`fn`), then removes the temporary directory and resolves or rejects
|
||||||
|
based on the result of `fn`.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const fs = require('@npmcli/fs')
|
||||||
|
const os = require('os')
|
||||||
|
|
||||||
|
// this function will be called with the full path to the temporary directory
|
||||||
|
// it is called with `await` behind the scenes, so can be async if desired.
|
||||||
|
const myFunction = async (tempPath) => {
|
||||||
|
return 'done!'
|
||||||
|
}
|
||||||
|
|
||||||
|
const main = async () => {
|
||||||
|
const result = await fs.withTempDir(os.tmpdir(), myFunction)
|
||||||
|
// result === 'done!'
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
|
## `fs.readdirScoped(root) -> Promise`
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
|
||||||
|
- `root`: the directory to read
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
Like `fs.readdir` but handling `@org/module` dirs as if they were
|
||||||
|
a single entry.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const readdir = require('readdir-scoped-modules')
|
||||||
|
const entries = await readdir('node_modules')
|
||||||
|
// entries will be something like: ['a', '@org/foo', '@org/bar']
|
||||||
|
```
|
||||||
|
|
||||||
|
## `fs.moveFile(source, dest, options) -> Promise`
|
||||||
|
|
||||||
|
A fork of [move-file](https://github.com/sindresorhus/move-file) with
|
||||||
|
support for Common JS.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- Promise API.
|
||||||
|
- Supports moving a file across partitions and devices.
|
||||||
|
- Optionally prevent overwriting an existing file.
|
||||||
|
- Creates non-existent destination directories for you.
|
||||||
|
- Automatically recurses when source is a directory.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
|
||||||
|
- `source`: File, or directory, you want to move.
|
||||||
|
- `dest`: Where you want the file or directory moved.
|
||||||
|
- `options`
|
||||||
|
- `overwrite` (`boolean`, default: `true`): Overwrite existing destination file(s).
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
The built-in
|
||||||
|
[`fs.rename()`](https://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback)
|
||||||
|
is just a JavaScript wrapper for the C `rename(2)` function, which doesn't
|
||||||
|
support moving files across partitions or devices. This module is what you
|
||||||
|
would have expected `fs.rename()` to be.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const { moveFile } = require('@npmcli/fs');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await moveFile('source/unicorn.png', 'destination/unicorn.png');
|
||||||
|
console.log('The file has been moved');
|
||||||
|
})();
|
||||||
|
```
|
@ -0,0 +1,20 @@
|
|||||||
|
// given an input that may or may not be an object, return an object that has
|
||||||
|
// a copy of every defined property listed in 'copy'. if the input is not an
|
||||||
|
// object, assign it to the property named by 'wrap'
|
||||||
|
const getOptions = (input, { copy, wrap }) => {
|
||||||
|
const result = {}
|
||||||
|
|
||||||
|
if (input && typeof input === 'object') {
|
||||||
|
for (const prop of copy) {
|
||||||
|
if (input[prop] !== undefined) {
|
||||||
|
result[prop] = input[prop]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result[wrap] = input
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = getOptions
|
@ -0,0 +1,9 @@
|
|||||||
|
const semver = require('semver')
|
||||||
|
|
||||||
|
const satisfies = (range) => {
|
||||||
|
return semver.satisfies(process.version, range, { includePrerelease: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
satisfies,
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
(The MIT License)
|
||||||
|
|
||||||
|
Copyright (c) 2011-2017 JP Richardson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
|
||||||
|
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
|
||||||
|
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||||
|
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
|
||||||
|
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,129 @@
|
|||||||
|
'use strict'
|
||||||
|
const { inspect } = require('util')
|
||||||
|
|
||||||
|
// adapted from node's internal/errors
|
||||||
|
// https://github.com/nodejs/node/blob/c8a04049/lib/internal/errors.js
|
||||||
|
|
||||||
|
// close copy of node's internal SystemError class.
|
||||||
|
class SystemError {
|
||||||
|
constructor (code, prefix, context) {
|
||||||
|
// XXX context.code is undefined in all constructors used in cp/polyfill
|
||||||
|
// that may be a bug copied from node, maybe the constructor should use
|
||||||
|
// `code` not `errno`? nodejs/node#41104
|
||||||
|
let message = `${prefix}: ${context.syscall} returned ` +
|
||||||
|
`${context.code} (${context.message})`
|
||||||
|
|
||||||
|
if (context.path !== undefined) {
|
||||||
|
message += ` ${context.path}`
|
||||||
|
}
|
||||||
|
if (context.dest !== undefined) {
|
||||||
|
message += ` => ${context.dest}`
|
||||||
|
}
|
||||||
|
|
||||||
|
this.code = code
|
||||||
|
Object.defineProperties(this, {
|
||||||
|
name: {
|
||||||
|
value: 'SystemError',
|
||||||
|
enumerable: false,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
value: message,
|
||||||
|
enumerable: false,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
value: context,
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
writable: false,
|
||||||
|
},
|
||||||
|
errno: {
|
||||||
|
get () {
|
||||||
|
return context.errno
|
||||||
|
},
|
||||||
|
set (value) {
|
||||||
|
context.errno = value
|
||||||
|
},
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
},
|
||||||
|
syscall: {
|
||||||
|
get () {
|
||||||
|
return context.syscall
|
||||||
|
},
|
||||||
|
set (value) {
|
||||||
|
context.syscall = value
|
||||||
|
},
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (context.path !== undefined) {
|
||||||
|
Object.defineProperty(this, 'path', {
|
||||||
|
get () {
|
||||||
|
return context.path
|
||||||
|
},
|
||||||
|
set (value) {
|
||||||
|
context.path = value
|
||||||
|
},
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.dest !== undefined) {
|
||||||
|
Object.defineProperty(this, 'dest', {
|
||||||
|
get () {
|
||||||
|
return context.dest
|
||||||
|
},
|
||||||
|
set (value) {
|
||||||
|
context.dest = value
|
||||||
|
},
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toString () {
|
||||||
|
return `${this.name} [${this.code}]: ${this.message}`
|
||||||
|
}
|
||||||
|
|
||||||
|
[Symbol.for('nodejs.util.inspect.custom')] (_recurseTimes, ctx) {
|
||||||
|
return inspect(this, {
|
||||||
|
...ctx,
|
||||||
|
getters: true,
|
||||||
|
customInspect: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function E (code, message) {
|
||||||
|
module.exports[code] = class NodeError extends SystemError {
|
||||||
|
constructor (ctx) {
|
||||||
|
super(code, message, ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite directory with non-directory')
|
||||||
|
E('ERR_FS_CP_EEXIST', 'Target already exists')
|
||||||
|
E('ERR_FS_CP_EINVAL', 'Invalid src or dest')
|
||||||
|
E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe')
|
||||||
|
E('ERR_FS_CP_NON_DIR_TO_DIR', 'Cannot overwrite non-directory with directory')
|
||||||
|
E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file')
|
||||||
|
E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY', 'Cannot overwrite symlink in subdirectory of self')
|
||||||
|
E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type')
|
||||||
|
E('ERR_FS_EISDIR', 'Path is a directory')
|
||||||
|
|
||||||
|
module.exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends Error {
|
||||||
|
constructor (name, expected, actual) {
|
||||||
|
super()
|
||||||
|
this.code = 'ERR_INVALID_ARG_TYPE'
|
||||||
|
this.message = `The ${name} argument must be ${expected}. Received ${typeof actual}`
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
const fs = require('fs/promises')
|
||||||
|
const getOptions = require('../common/get-options.js')
|
||||||
|
const node = require('../common/node.js')
|
||||||
|
const polyfill = require('./polyfill.js')
|
||||||
|
|
||||||
|
// node 16.7.0 added fs.cp
|
||||||
|
const useNative = node.satisfies('>=16.7.0')
|
||||||
|
|
||||||
|
const cp = async (src, dest, opts) => {
|
||||||
|
const options = getOptions(opts, {
|
||||||
|
copy: ['dereference', 'errorOnExist', 'filter', 'force', 'preserveTimestamps', 'recursive'],
|
||||||
|
})
|
||||||
|
|
||||||
|
// the polyfill is tested separately from this module, no need to hack
|
||||||
|
// process.version to try to trigger it just for coverage
|
||||||
|
// istanbul ignore next
|
||||||
|
return useNative
|
||||||
|
? fs.cp(src, dest, options)
|
||||||
|
: polyfill(src, dest, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = cp
|
@ -0,0 +1,428 @@
|
|||||||
|
// this file is a modified version of the code in node 17.2.0
|
||||||
|
// which is, in turn, a modified version of the fs-extra module on npm
|
||||||
|
// node core changes:
|
||||||
|
// - Use of the assert module has been replaced with core's error system.
|
||||||
|
// - All code related to the glob dependency has been removed.
|
||||||
|
// - Bring your own custom fs module is not currently supported.
|
||||||
|
// - Some basic code cleanup.
|
||||||
|
// changes here:
|
||||||
|
// - remove all callback related code
|
||||||
|
// - drop sync support
|
||||||
|
// - change assertions back to non-internal methods (see options.js)
|
||||||
|
// - throws ENOTDIR when rmdir gets an ENOENT for a path that exists in Windows
|
||||||
|
'use strict'
|
||||||
|
|
||||||
|
const {
|
||||||
|
ERR_FS_CP_DIR_TO_NON_DIR,
|
||||||
|
ERR_FS_CP_EEXIST,
|
||||||
|
ERR_FS_CP_EINVAL,
|
||||||
|
ERR_FS_CP_FIFO_PIPE,
|
||||||
|
ERR_FS_CP_NON_DIR_TO_DIR,
|
||||||
|
ERR_FS_CP_SOCKET,
|
||||||
|
ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY,
|
||||||
|
ERR_FS_CP_UNKNOWN,
|
||||||
|
ERR_FS_EISDIR,
|
||||||
|
ERR_INVALID_ARG_TYPE,
|
||||||
|
} = require('./errors.js')
|
||||||
|
const {
|
||||||
|
constants: {
|
||||||
|
errno: {
|
||||||
|
EEXIST,
|
||||||
|
EISDIR,
|
||||||
|
EINVAL,
|
||||||
|
ENOTDIR,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} = require('os')
|
||||||
|
const {
|
||||||
|
chmod,
|
||||||
|
copyFile,
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
readdir,
|
||||||
|
readlink,
|
||||||
|
stat,
|
||||||
|
symlink,
|
||||||
|
unlink,
|
||||||
|
utimes,
|
||||||
|
} = require('fs/promises')
|
||||||
|
const {
|
||||||
|
dirname,
|
||||||
|
isAbsolute,
|
||||||
|
join,
|
||||||
|
parse,
|
||||||
|
resolve,
|
||||||
|
sep,
|
||||||
|
toNamespacedPath,
|
||||||
|
} = require('path')
|
||||||
|
const { fileURLToPath } = require('url')
|
||||||
|
|
||||||
|
const defaultOptions = {
|
||||||
|
dereference: false,
|
||||||
|
errorOnExist: false,
|
||||||
|
filter: undefined,
|
||||||
|
force: true,
|
||||||
|
preserveTimestamps: false,
|
||||||
|
recursive: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cp (src, dest, opts) {
|
||||||
|
if (opts != null && typeof opts !== 'object') {
|
||||||
|
throw new ERR_INVALID_ARG_TYPE('options', ['Object'], opts)
|
||||||
|
}
|
||||||
|
return cpFn(
|
||||||
|
toNamespacedPath(getValidatedPath(src)),
|
||||||
|
toNamespacedPath(getValidatedPath(dest)),
|
||||||
|
{ ...defaultOptions, ...opts })
|
||||||
|
}
|
||||||
|
|
||||||
|
function getValidatedPath (fileURLOrPath) {
|
||||||
|
const path = fileURLOrPath != null && fileURLOrPath.href
|
||||||
|
&& fileURLOrPath.origin
|
||||||
|
? fileURLToPath(fileURLOrPath)
|
||||||
|
: fileURLOrPath
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cpFn (src, dest, opts) {
|
||||||
|
// Warn about using preserveTimestamps on 32-bit node
|
||||||
|
// istanbul ignore next
|
||||||
|
if (opts.preserveTimestamps && process.arch === 'ia32') {
|
||||||
|
const warning = 'Using the preserveTimestamps option in 32-bit ' +
|
||||||
|
'node is not recommended'
|
||||||
|
process.emitWarning(warning, 'TimestampPrecisionWarning')
|
||||||
|
}
|
||||||
|
const stats = await checkPaths(src, dest, opts)
|
||||||
|
const { srcStat, destStat } = stats
|
||||||
|
await checkParentPaths(src, srcStat, dest)
|
||||||
|
if (opts.filter) {
|
||||||
|
return handleFilter(checkParentDir, destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
return checkParentDir(destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkPaths (src, dest, opts) {
|
||||||
|
const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts)
|
||||||
|
if (destStat) {
|
||||||
|
if (areIdentical(srcStat, destStat)) {
|
||||||
|
throw new ERR_FS_CP_EINVAL({
|
||||||
|
message: 'src and dest cannot be the same',
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (srcStat.isDirectory() && !destStat.isDirectory()) {
|
||||||
|
throw new ERR_FS_CP_DIR_TO_NON_DIR({
|
||||||
|
message: `cannot overwrite directory ${src} ` +
|
||||||
|
`with non-directory ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EISDIR,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (!srcStat.isDirectory() && destStat.isDirectory()) {
|
||||||
|
throw new ERR_FS_CP_NON_DIR_TO_DIR({
|
||||||
|
message: `cannot overwrite non-directory ${src} ` +
|
||||||
|
`with directory ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: ENOTDIR,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
|
||||||
|
throw new ERR_FS_CP_EINVAL({
|
||||||
|
message: `cannot copy ${src} to a subdirectory of self ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { srcStat, destStat }
|
||||||
|
}
|
||||||
|
|
||||||
|
function areIdentical (srcStat, destStat) {
|
||||||
|
return destStat.ino && destStat.dev && destStat.ino === srcStat.ino &&
|
||||||
|
destStat.dev === srcStat.dev
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStats (src, dest, opts) {
|
||||||
|
const statFunc = opts.dereference ?
|
||||||
|
(file) => stat(file, { bigint: true }) :
|
||||||
|
(file) => lstat(file, { bigint: true })
|
||||||
|
return Promise.all([
|
||||||
|
statFunc(src),
|
||||||
|
statFunc(dest).catch((err) => {
|
||||||
|
// istanbul ignore next: unsure how to cover.
|
||||||
|
if (err.code === 'ENOENT') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
// istanbul ignore next: unsure how to cover.
|
||||||
|
throw err
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkParentDir (destStat, src, dest, opts) {
|
||||||
|
const destParent = dirname(dest)
|
||||||
|
const dirExists = await pathExists(destParent)
|
||||||
|
if (dirExists) {
|
||||||
|
return getStatsForCopy(destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
await mkdir(destParent, { recursive: true })
|
||||||
|
return getStatsForCopy(destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
function pathExists (dest) {
|
||||||
|
return stat(dest).then(
|
||||||
|
() => true,
|
||||||
|
// istanbul ignore next: not sure when this would occur
|
||||||
|
(err) => (err.code === 'ENOENT' ? false : Promise.reject(err)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively check if dest parent is a subdirectory of src.
|
||||||
|
// It works for all file types including symlinks since it
|
||||||
|
// checks the src and dest inodes. It starts from the deepest
|
||||||
|
// parent and stops once it reaches the src parent or the root path.
|
||||||
|
async function checkParentPaths (src, srcStat, dest) {
|
||||||
|
const srcParent = resolve(dirname(src))
|
||||||
|
const destParent = resolve(dirname(dest))
|
||||||
|
if (destParent === srcParent || destParent === parse(destParent).root) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let destStat
|
||||||
|
try {
|
||||||
|
destStat = await stat(destParent, { bigint: true })
|
||||||
|
} catch (err) {
|
||||||
|
// istanbul ignore else: not sure when this would occur
|
||||||
|
if (err.code === 'ENOENT') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// istanbul ignore next: not sure when this would occur
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
if (areIdentical(srcStat, destStat)) {
|
||||||
|
throw new ERR_FS_CP_EINVAL({
|
||||||
|
message: `cannot copy ${src} to a subdirectory of self ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return checkParentPaths(src, srcStat, destParent)
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizePathToArray = (path) =>
|
||||||
|
resolve(path).split(sep).filter(Boolean)
|
||||||
|
|
||||||
|
// Return true if dest is a subdir of src, otherwise false.
|
||||||
|
// It only checks the path strings.
|
||||||
|
function isSrcSubdir (src, dest) {
|
||||||
|
const srcArr = normalizePathToArray(src)
|
||||||
|
const destArr = normalizePathToArray(dest)
|
||||||
|
return srcArr.every((cur, i) => destArr[i] === cur)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFilter (onInclude, destStat, src, dest, opts, cb) {
|
||||||
|
const include = await opts.filter(src, dest)
|
||||||
|
if (include) {
|
||||||
|
return onInclude(destStat, src, dest, opts, cb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCopy (destStat, src, dest, opts) {
|
||||||
|
if (opts.filter) {
|
||||||
|
return handleFilter(getStatsForCopy, destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
return getStatsForCopy(destStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getStatsForCopy (destStat, src, dest, opts) {
|
||||||
|
const statFn = opts.dereference ? stat : lstat
|
||||||
|
const srcStat = await statFn(src)
|
||||||
|
// istanbul ignore else: can't portably test FIFO
|
||||||
|
if (srcStat.isDirectory() && opts.recursive) {
|
||||||
|
return onDir(srcStat, destStat, src, dest, opts)
|
||||||
|
} else if (srcStat.isDirectory()) {
|
||||||
|
throw new ERR_FS_EISDIR({
|
||||||
|
message: `${src} is a directory (not copied)`,
|
||||||
|
path: src,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
} else if (srcStat.isFile() ||
|
||||||
|
srcStat.isCharacterDevice() ||
|
||||||
|
srcStat.isBlockDevice()) {
|
||||||
|
return onFile(srcStat, destStat, src, dest, opts)
|
||||||
|
} else if (srcStat.isSymbolicLink()) {
|
||||||
|
return onLink(destStat, src, dest)
|
||||||
|
} else if (srcStat.isSocket()) {
|
||||||
|
throw new ERR_FS_CP_SOCKET({
|
||||||
|
message: `cannot copy a socket file: ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
} else if (srcStat.isFIFO()) {
|
||||||
|
throw new ERR_FS_CP_FIFO_PIPE({
|
||||||
|
message: `cannot copy a FIFO pipe: ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// istanbul ignore next: should be unreachable
|
||||||
|
throw new ERR_FS_CP_UNKNOWN({
|
||||||
|
message: `cannot copy an unknown file type: ${dest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function onFile (srcStat, destStat, src, dest, opts) {
|
||||||
|
if (!destStat) {
|
||||||
|
return _copyFile(srcStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
return mayCopyFile(srcStat, src, dest, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mayCopyFile (srcStat, src, dest, opts) {
|
||||||
|
if (opts.force) {
|
||||||
|
await unlink(dest)
|
||||||
|
return _copyFile(srcStat, src, dest, opts)
|
||||||
|
} else if (opts.errorOnExist) {
|
||||||
|
throw new ERR_FS_CP_EEXIST({
|
||||||
|
message: `${dest} already exists`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EEXIST,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function _copyFile (srcStat, src, dest, opts) {
|
||||||
|
await copyFile(src, dest)
|
||||||
|
if (opts.preserveTimestamps) {
|
||||||
|
return handleTimestampsAndMode(srcStat.mode, src, dest)
|
||||||
|
}
|
||||||
|
return setDestMode(dest, srcStat.mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleTimestampsAndMode (srcMode, src, dest) {
|
||||||
|
// Make sure the file is writable before setting the timestamp
|
||||||
|
// otherwise open fails with EPERM when invoked with 'r+'
|
||||||
|
// (through utimes call)
|
||||||
|
if (fileIsNotWritable(srcMode)) {
|
||||||
|
await makeFileWritable(dest, srcMode)
|
||||||
|
return setDestTimestampsAndMode(srcMode, src, dest)
|
||||||
|
}
|
||||||
|
return setDestTimestampsAndMode(srcMode, src, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileIsNotWritable (srcMode) {
|
||||||
|
return (srcMode & 0o200) === 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeFileWritable (dest, srcMode) {
|
||||||
|
return setDestMode(dest, srcMode | 0o200)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setDestTimestampsAndMode (srcMode, src, dest) {
|
||||||
|
await setDestTimestamps(src, dest)
|
||||||
|
return setDestMode(dest, srcMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDestMode (dest, srcMode) {
|
||||||
|
return chmod(dest, srcMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setDestTimestamps (src, dest) {
|
||||||
|
// The initial srcStat.atime cannot be trusted
|
||||||
|
// because it is modified by the read(2) system call
|
||||||
|
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
|
||||||
|
const updatedSrcStat = await stat(src)
|
||||||
|
return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDir (srcStat, destStat, src, dest, opts) {
|
||||||
|
if (!destStat) {
|
||||||
|
return mkDirAndCopy(srcStat.mode, src, dest, opts)
|
||||||
|
}
|
||||||
|
return copyDir(src, dest, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mkDirAndCopy (srcMode, src, dest, opts) {
|
||||||
|
await mkdir(dest)
|
||||||
|
await copyDir(src, dest, opts)
|
||||||
|
return setDestMode(dest, srcMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyDir (src, dest, opts) {
|
||||||
|
const dir = await readdir(src)
|
||||||
|
for (let i = 0; i < dir.length; i++) {
|
||||||
|
const item = dir[i]
|
||||||
|
const srcItem = join(src, item)
|
||||||
|
const destItem = join(dest, item)
|
||||||
|
const { destStat } = await checkPaths(srcItem, destItem, opts)
|
||||||
|
await startCopy(destStat, srcItem, destItem, opts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onLink (destStat, src, dest) {
|
||||||
|
let resolvedSrc = await readlink(src)
|
||||||
|
if (!isAbsolute(resolvedSrc)) {
|
||||||
|
resolvedSrc = resolve(dirname(src), resolvedSrc)
|
||||||
|
}
|
||||||
|
if (!destStat) {
|
||||||
|
return symlink(resolvedSrc, dest)
|
||||||
|
}
|
||||||
|
let resolvedDest
|
||||||
|
try {
|
||||||
|
resolvedDest = await readlink(dest)
|
||||||
|
} catch (err) {
|
||||||
|
// Dest exists and is a regular file or directory,
|
||||||
|
// Windows may throw UNKNOWN error. If dest already exists,
|
||||||
|
// fs throws error anyway, so no need to guard against it here.
|
||||||
|
// istanbul ignore next: can only test on windows
|
||||||
|
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') {
|
||||||
|
return symlink(resolvedSrc, dest)
|
||||||
|
}
|
||||||
|
// istanbul ignore next: should not be possible
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
if (!isAbsolute(resolvedDest)) {
|
||||||
|
resolvedDest = resolve(dirname(dest), resolvedDest)
|
||||||
|
}
|
||||||
|
if (isSrcSubdir(resolvedSrc, resolvedDest)) {
|
||||||
|
throw new ERR_FS_CP_EINVAL({
|
||||||
|
message: `cannot copy ${resolvedSrc} to a subdirectory of self ` +
|
||||||
|
`${resolvedDest}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Do not copy if src is a subdir of dest since unlinking
|
||||||
|
// dest in this case would result in removing src contents
|
||||||
|
// and therefore a broken symlink would be created.
|
||||||
|
const srcStat = await stat(src)
|
||||||
|
if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) {
|
||||||
|
throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({
|
||||||
|
message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`,
|
||||||
|
path: dest,
|
||||||
|
syscall: 'cp',
|
||||||
|
errno: EINVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return copyLink(resolvedSrc, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyLink (resolvedSrc, dest) {
|
||||||
|
await unlink(dest)
|
||||||
|
return symlink(resolvedSrc, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = cp
|
@ -0,0 +1,13 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
const cp = require('./cp/index.js')
|
||||||
|
const withTempDir = require('./with-temp-dir.js')
|
||||||
|
const readdirScoped = require('./readdir-scoped.js')
|
||||||
|
const moveFile = require('./move-file.js')
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
cp,
|
||||||
|
withTempDir,
|
||||||
|
readdirScoped,
|
||||||
|
moveFile,
|
||||||
|
}
|
@ -0,0 +1,78 @@
|
|||||||
|
const { dirname, join, resolve, relative, isAbsolute } = require('path')
|
||||||
|
const fs = require('fs/promises')
|
||||||
|
|
||||||
|
const pathExists = async path => {
|
||||||
|
try {
|
||||||
|
await fs.access(path)
|
||||||
|
return true
|
||||||
|
} catch (er) {
|
||||||
|
return er.code !== 'ENOENT'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => {
|
||||||
|
if (!source || !destination) {
|
||||||
|
throw new TypeError('`source` and `destination` file required')
|
||||||
|
}
|
||||||
|
|
||||||
|
options = {
|
||||||
|
overwrite: true,
|
||||||
|
...options,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.overwrite && await pathExists(destination)) {
|
||||||
|
throw new Error(`The destination file exists: ${destination}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.mkdir(dirname(destination), { recursive: true })
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.rename(source, destination)
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'EXDEV' || error.code === 'EPERM') {
|
||||||
|
const sourceStat = await fs.lstat(source)
|
||||||
|
if (sourceStat.isDirectory()) {
|
||||||
|
const files = await fs.readdir(source)
|
||||||
|
await Promise.all(files.map((file) =>
|
||||||
|
moveFile(join(source, file), join(destination, file), options, false, symlinks)
|
||||||
|
))
|
||||||
|
} else if (sourceStat.isSymbolicLink()) {
|
||||||
|
symlinks.push({ source, destination })
|
||||||
|
} else {
|
||||||
|
await fs.copyFile(source, destination)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (root) {
|
||||||
|
await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => {
|
||||||
|
let target = await fs.readlink(symSource)
|
||||||
|
// junction symlinks in windows will be absolute paths, so we need to
|
||||||
|
// make sure they point to the symlink destination
|
||||||
|
if (isAbsolute(target)) {
|
||||||
|
target = resolve(symDestination, relative(symSource, target))
|
||||||
|
}
|
||||||
|
// try to determine what the actual file is so we can create the correct
|
||||||
|
// type of symlink in windows
|
||||||
|
let targetStat = 'file'
|
||||||
|
try {
|
||||||
|
targetStat = await fs.stat(resolve(dirname(symSource), target))
|
||||||
|
if (targetStat.isDirectory()) {
|
||||||
|
targetStat = 'junction'
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// targetStat remains 'file'
|
||||||
|
}
|
||||||
|
await fs.symlink(
|
||||||
|
target,
|
||||||
|
symDestination,
|
||||||
|
targetStat
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
await fs.rm(source, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = moveFile
|
@ -0,0 +1,20 @@
|
|||||||
|
const { readdir } = require('fs/promises')
|
||||||
|
const { join } = require('path')
|
||||||
|
|
||||||
|
const readdirScoped = async (dir) => {
|
||||||
|
const results = []
|
||||||
|
|
||||||
|
for (const item of await readdir(dir)) {
|
||||||
|
if (item.startsWith('@')) {
|
||||||
|
for (const scopedItem of await readdir(join(dir, item))) {
|
||||||
|
results.push(join(item, scopedItem))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
results.push(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = readdirScoped
|
@ -0,0 +1,39 @@
|
|||||||
|
const { join, sep } = require('path')
|
||||||
|
|
||||||
|
const getOptions = require('./common/get-options.js')
|
||||||
|
const { mkdir, mkdtemp, rm } = require('fs/promises')
|
||||||
|
|
||||||
|
// create a temp directory, ensure its permissions match its parent, then call
|
||||||
|
// the supplied function passing it the path to the directory. clean up after
|
||||||
|
// the function finishes, whether it throws or not
|
||||||
|
const withTempDir = async (root, fn, opts) => {
|
||||||
|
const options = getOptions(opts, {
|
||||||
|
copy: ['tmpPrefix'],
|
||||||
|
})
|
||||||
|
// create the directory
|
||||||
|
await mkdir(root, { recursive: true })
|
||||||
|
|
||||||
|
const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || ''))
|
||||||
|
let err
|
||||||
|
let result
|
||||||
|
|
||||||
|
try {
|
||||||
|
result = await fn(target)
|
||||||
|
} catch (_err) {
|
||||||
|
err = _err
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await rm(target, { force: true, recursive: true })
|
||||||
|
} catch {
|
||||||
|
// ignore errors
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = withTempDir
|
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||||
|
|
||||||
|
case `uname` in
|
||||||
|
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -x "$basedir/node" ]; then
|
||||||
|
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
|
||||||
|
else
|
||||||
|
exec node "$basedir/../semver/bin/semver.js" "$@"
|
||||||
|
fi
|
@ -0,0 +1,17 @@
|
|||||||
|
@ECHO off
|
||||||
|
GOTO start
|
||||||
|
:find_dp0
|
||||||
|
SET dp0=%~dp0
|
||||||
|
EXIT /b
|
||||||
|
:start
|
||||||
|
SETLOCAL
|
||||||
|
CALL :find_dp0
|
||||||
|
|
||||||
|
IF EXIST "%dp0%\node.exe" (
|
||||||
|
SET "_prog=%dp0%\node.exe"
|
||||||
|
) ELSE (
|
||||||
|
SET "_prog=node"
|
||||||
|
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
|
)
|
||||||
|
|
||||||
|
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env pwsh
|
||||||
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||||
|
|
||||||
|
$exe=""
|
||||||
|
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||||
|
# Fix case when both the Windows and Linux builds of Node
|
||||||
|
# are installed in the same directory
|
||||||
|
$exe=".exe"
|
||||||
|
}
|
||||||
|
$ret=0
|
||||||
|
if (Test-Path "$basedir/node$exe") {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||||
|
} else {
|
||||||
|
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
} else {
|
||||||
|
# Support pipeline input
|
||||||
|
if ($MyInvocation.ExpectingInput) {
|
||||||
|
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||||
|
} else {
|
||||||
|
& "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||||
|
}
|
||||||
|
$ret=$LASTEXITCODE
|
||||||
|
}
|
||||||
|
exit $ret
|
@ -0,0 +1,15 @@
|
|||||||
|
The ISC License
|
||||||
|
|
||||||
|
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted, provided that the above
|
||||||
|
copyright notice and this permission notice appear in all copies.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||||
|
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||||
|
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||||
|
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||||
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||||
|
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
@ -0,0 +1,166 @@
|
|||||||
|
# lru cache
|
||||||
|
|
||||||
|
A cache object that deletes the least-recently-used items.
|
||||||
|
|
||||||
|
[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache)
|
||||||
|
|
||||||
|
## Installation:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
npm install lru-cache --save
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var LRU = require("lru-cache")
|
||||||
|
, options = { max: 500
|
||||||
|
, length: function (n, key) { return n * 2 + key.length }
|
||||||
|
, dispose: function (key, n) { n.close() }
|
||||||
|
, maxAge: 1000 * 60 * 60 }
|
||||||
|
, cache = new LRU(options)
|
||||||
|
, otherCache = new LRU(50) // sets just the max size
|
||||||
|
|
||||||
|
cache.set("key", "value")
|
||||||
|
cache.get("key") // "value"
|
||||||
|
|
||||||
|
// non-string keys ARE fully supported
|
||||||
|
// but note that it must be THE SAME object, not
|
||||||
|
// just a JSON-equivalent object.
|
||||||
|
var someObject = { a: 1 }
|
||||||
|
cache.set(someObject, 'a value')
|
||||||
|
// Object keys are not toString()-ed
|
||||||
|
cache.set('[object Object]', 'a different value')
|
||||||
|
assert.equal(cache.get(someObject), 'a value')
|
||||||
|
// A similar object with same keys/values won't work,
|
||||||
|
// because it's a different object identity
|
||||||
|
assert.equal(cache.get({ a: 1 }), undefined)
|
||||||
|
|
||||||
|
cache.reset() // empty the cache
|
||||||
|
```
|
||||||
|
|
||||||
|
If you put more stuff in it, then items will fall out.
|
||||||
|
|
||||||
|
If you try to put an oversized thing in it, then it'll fall out right
|
||||||
|
away.
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
* `max` The maximum size of the cache, checked by applying the length
|
||||||
|
function to all values in the cache. Not setting this is kind of
|
||||||
|
silly, since that's the whole purpose of this lib, but it defaults
|
||||||
|
to `Infinity`. Setting it to a non-number or negative number will
|
||||||
|
throw a `TypeError`. Setting it to 0 makes it be `Infinity`.
|
||||||
|
* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
|
||||||
|
as they age, but if you try to get an item that is too old, it'll
|
||||||
|
drop it and return undefined instead of giving it to you.
|
||||||
|
Setting this to a negative value will make everything seem old!
|
||||||
|
Setting it to a non-number will throw a `TypeError`.
|
||||||
|
* `length` Function that is used to calculate the length of stored
|
||||||
|
items. If you're storing strings or buffers, then you probably want
|
||||||
|
to do something like `function(n, key){return n.length}`. The default is
|
||||||
|
`function(){return 1}`, which is fine if you want to store `max`
|
||||||
|
like-sized things. The item is passed as the first argument, and
|
||||||
|
the key is passed as the second argumnet.
|
||||||
|
* `dispose` Function that is called on items when they are dropped
|
||||||
|
from the cache. This can be handy if you want to close file
|
||||||
|
descriptors or do other cleanup tasks when items are no longer
|
||||||
|
accessible. Called with `key, value`. It's called *before*
|
||||||
|
actually removing the item from the internal cache, so if you want
|
||||||
|
to immediately put it back in, you'll have to do that in a
|
||||||
|
`nextTick` or `setTimeout` callback or it won't do anything.
|
||||||
|
* `stale` By default, if you set a `maxAge`, it'll only actually pull
|
||||||
|
stale items out of the cache when you `get(key)`. (That is, it's
|
||||||
|
not pre-emptively doing a `setTimeout` or anything.) If you set
|
||||||
|
`stale:true`, it'll return the stale value before deleting it. If
|
||||||
|
you don't set this, then it'll return `undefined` when you try to
|
||||||
|
get a stale entry, as if it had already been deleted.
|
||||||
|
* `noDisposeOnSet` By default, if you set a `dispose()` method, then
|
||||||
|
it'll be called whenever a `set()` operation overwrites an existing
|
||||||
|
key. If you set this option, `dispose()` will only be called when a
|
||||||
|
key falls out of the cache, not when it is overwritten.
|
||||||
|
* `updateAgeOnGet` When using time-expiring entries with `maxAge`,
|
||||||
|
setting this to `true` will make each item's effective time update
|
||||||
|
to the current time whenever it is retrieved from cache, causing it
|
||||||
|
to not expire. (It can still fall out of cache based on recency of
|
||||||
|
use, of course.)
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
* `set(key, value, maxAge)`
|
||||||
|
* `get(key) => value`
|
||||||
|
|
||||||
|
Both of these will update the "recently used"-ness of the key.
|
||||||
|
They do what you think. `maxAge` is optional and overrides the
|
||||||
|
cache `maxAge` option if provided.
|
||||||
|
|
||||||
|
If the key is not found, `get()` will return `undefined`.
|
||||||
|
|
||||||
|
The key and val can be any value.
|
||||||
|
|
||||||
|
* `peek(key)`
|
||||||
|
|
||||||
|
Returns the key value (or `undefined` if not found) without
|
||||||
|
updating the "recently used"-ness of the key.
|
||||||
|
|
||||||
|
(If you find yourself using this a lot, you *might* be using the
|
||||||
|
wrong sort of data structure, but there are some use cases where
|
||||||
|
it's handy.)
|
||||||
|
|
||||||
|
* `del(key)`
|
||||||
|
|
||||||
|
Deletes a key out of the cache.
|
||||||
|
|
||||||
|
* `reset()`
|
||||||
|
|
||||||
|
Clear the cache entirely, throwing away all values.
|
||||||
|
|
||||||
|
* `has(key)`
|
||||||
|
|
||||||
|
Check if a key is in the cache, without updating the recent-ness
|
||||||
|
or deleting it for being stale.
|
||||||
|
|
||||||
|
* `forEach(function(value,key,cache), [thisp])`
|
||||||
|
|
||||||
|
Just like `Array.prototype.forEach`. Iterates over all the keys
|
||||||
|
in the cache, in order of recent-ness. (Ie, more recently used
|
||||||
|
items are iterated over first.)
|
||||||
|
|
||||||
|
* `rforEach(function(value,key,cache), [thisp])`
|
||||||
|
|
||||||
|
The same as `cache.forEach(...)` but items are iterated over in
|
||||||
|
reverse order. (ie, less recently used items are iterated over
|
||||||
|
first.)
|
||||||
|
|
||||||
|
* `keys()`
|
||||||
|
|
||||||
|
Return an array of the keys in the cache.
|
||||||
|
|
||||||
|
* `values()`
|
||||||
|
|
||||||
|
Return an array of the values in the cache.
|
||||||
|
|
||||||
|
* `length`
|
||||||
|
|
||||||
|
Return total length of objects in cache taking into account
|
||||||
|
`length` options function.
|
||||||
|
|
||||||
|
* `itemCount`
|
||||||
|
|
||||||
|
Return total quantity of objects currently in cache. Note, that
|
||||||
|
`stale` (see options) items are returned as part of this item
|
||||||
|
count.
|
||||||
|
|
||||||
|
* `dump()`
|
||||||
|
|
||||||
|
Return an array of the cache entries ready for serialization and usage
|
||||||
|
with 'destinationCache.load(arr)`.
|
||||||
|
|
||||||
|
* `load(cacheEntriesArray)`
|
||||||
|
|
||||||
|
Loads another cache entries array, obtained with `sourceCache.dump()`,
|
||||||
|
into the cache. The destination cache is reset before loading new entries
|
||||||
|
|
||||||
|
* `prune()`
|
||||||
|
|
||||||
|
Manually iterates over the entire cache proactively pruning old entries
|
@ -0,0 +1,334 @@
|
|||||||
|
'use strict'
|
||||||
|
|
||||||
|
// A linked list to keep track of recently-used-ness
|
||||||
|
const Yallist = require('yallist')
|
||||||
|
|
||||||
|
const MAX = Symbol('max')
|
||||||
|
const LENGTH = Symbol('length')
|
||||||
|
const LENGTH_CALCULATOR = Symbol('lengthCalculator')
|
||||||
|
const ALLOW_STALE = Symbol('allowStale')
|
||||||
|
const MAX_AGE = Symbol('maxAge')
|
||||||
|
const DISPOSE = Symbol('dispose')
|
||||||
|
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
|
||||||
|
const LRU_LIST = Symbol('lruList')
|
||||||
|
const CACHE = Symbol('cache')
|
||||||
|
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
|
||||||
|
|
||||||
|
const naiveLength = () => 1
|
||||||
|
|
||||||
|
// lruList is a yallist where the head is the youngest
|
||||||
|
// item, and the tail is the oldest. the list contains the Hit
|
||||||
|
// objects as the entries.
|
||||||
|
// Each Hit object has a reference to its Yallist.Node. This
|
||||||
|
// never changes.
|
||||||
|
//
|
||||||
|
// cache is a Map (or PseudoMap) that matches the keys to
|
||||||
|
// the Yallist.Node object.
|
||||||
|
class LRUCache {
|
||||||
|
constructor (options) {
|
||||||
|
if (typeof options === 'number')
|
||||||
|
options = { max: options }
|
||||||
|
|
||||||
|
if (!options)
|
||||||
|
options = {}
|
||||||
|
|
||||||
|
if (options.max && (typeof options.max !== 'number' || options.max < 0))
|
||||||
|
throw new TypeError('max must be a non-negative number')
|
||||||
|
// Kind of weird to have a default max of Infinity, but oh well.
|
||||||
|
const max = this[MAX] = options.max || Infinity
|
||||||
|
|
||||||
|
const lc = options.length || naiveLength
|
||||||
|
this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
|
||||||
|
this[ALLOW_STALE] = options.stale || false
|
||||||
|
if (options.maxAge && typeof options.maxAge !== 'number')
|
||||||
|
throw new TypeError('maxAge must be a number')
|
||||||
|
this[MAX_AGE] = options.maxAge || 0
|
||||||
|
this[DISPOSE] = options.dispose
|
||||||
|
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
|
||||||
|
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
|
||||||
|
this.reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
// resize the cache when the max changes.
|
||||||
|
set max (mL) {
|
||||||
|
if (typeof mL !== 'number' || mL < 0)
|
||||||
|
throw new TypeError('max must be a non-negative number')
|
||||||
|
|
||||||
|
this[MAX] = mL || Infinity
|
||||||
|
trim(this)
|
||||||
|
}
|
||||||
|
get max () {
|
||||||
|
return this[MAX]
|
||||||
|
}
|
||||||
|
|
||||||
|
set allowStale (allowStale) {
|
||||||
|
this[ALLOW_STALE] = !!allowStale
|
||||||
|
}
|
||||||
|
get allowStale () {
|
||||||
|
return this[ALLOW_STALE]
|
||||||
|
}
|
||||||
|
|
||||||
|
set maxAge (mA) {
|
||||||
|
if (typeof mA !== 'number')
|
||||||
|
throw new TypeError('maxAge must be a non-negative number')
|
||||||
|
|
||||||
|
this[MAX_AGE] = mA
|
||||||
|
trim(this)
|
||||||
|
}
|
||||||
|
get maxAge () {
|
||||||
|
return this[MAX_AGE]
|
||||||
|
}
|
||||||
|
|
||||||
|
// resize the cache when the lengthCalculator changes.
|
||||||
|
set lengthCalculator (lC) {
|
||||||
|
if (typeof lC !== 'function')
|
||||||
|
lC = naiveLength
|
||||||
|
|
||||||
|
if (lC !== this[LENGTH_CALCULATOR]) {
|
||||||
|
this[LENGTH_CALCULATOR] = lC
|
||||||
|
this[LENGTH] = 0
|
||||||
|
this[LRU_LIST].forEach(hit => {
|
||||||
|
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
|
||||||
|
this[LENGTH] += hit.length
|
||||||
|
})
|
||||||
|
}
|
||||||
|
trim(this)
|
||||||
|
}
|
||||||
|
get lengthCalculator () { return this[LENGTH_CALCULATOR] }
|
||||||
|
|
||||||
|
get length () { return this[LENGTH] }
|
||||||
|
get itemCount () { return this[LRU_LIST].length }
|
||||||
|
|
||||||
|
rforEach (fn, thisp) {
|
||||||
|
thisp = thisp || this
|
||||||
|
for (let walker = this[LRU_LIST].tail; walker !== null;) {
|
||||||
|
const prev = walker.prev
|
||||||
|
forEachStep(this, fn, walker, thisp)
|
||||||
|
walker = prev
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
forEach (fn, thisp) {
|
||||||
|
thisp = thisp || this
|
||||||
|
for (let walker = this[LRU_LIST].head; walker !== null;) {
|
||||||
|
const next = walker.next
|
||||||
|
forEachStep(this, fn, walker, thisp)
|
||||||
|
walker = next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
keys () {
|
||||||
|
return this[LRU_LIST].toArray().map(k => k.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
values () {
|
||||||
|
return this[LRU_LIST].toArray().map(k => k.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
reset () {
|
||||||
|
if (this[DISPOSE] &&
|
||||||
|
this[LRU_LIST] &&
|
||||||
|
this[LRU_LIST].length) {
|
||||||
|
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
|
||||||
|
}
|
||||||
|
|
||||||
|
this[CACHE] = new Map() // hash of items by key
|
||||||
|
this[LRU_LIST] = new Yallist() // list of items in order of use recency
|
||||||
|
this[LENGTH] = 0 // length of items in the list
|
||||||
|
}
|
||||||
|
|
||||||
|
dump () {
|
||||||
|
return this[LRU_LIST].map(hit =>
|
||||||
|
isStale(this, hit) ? false : {
|
||||||
|
k: hit.key,
|
||||||
|
v: hit.value,
|
||||||
|
e: hit.now + (hit.maxAge || 0)
|
||||||
|
}).toArray().filter(h => h)
|
||||||
|
}
|
||||||
|
|
||||||
|
dumpLru () {
|
||||||
|
return this[LRU_LIST]
|
||||||
|
}
|
||||||
|
|
||||||
|
set (key, value, maxAge) {
|
||||||
|
maxAge = maxAge || this[MAX_AGE]
|
||||||
|
|
||||||
|
if (maxAge && typeof maxAge !== 'number')
|
||||||
|
throw new TypeError('maxAge must be a number')
|
||||||
|
|
||||||
|
const now = maxAge ? Date.now() : 0
|
||||||
|
const len = this[LENGTH_CALCULATOR](value, key)
|
||||||
|
|
||||||
|
if (this[CACHE].has(key)) {
|
||||||
|
if (len > this[MAX]) {
|
||||||
|
del(this, this[CACHE].get(key))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const node = this[CACHE].get(key)
|
||||||
|
const item = node.value
|
||||||
|
|
||||||
|
// dispose of the old one before overwriting
|
||||||
|
// split out into 2 ifs for better coverage tracking
|
||||||
|
if (this[DISPOSE]) {
|
||||||
|
if (!this[NO_DISPOSE_ON_SET])
|
||||||
|
this[DISPOSE](key, item.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
item.now = now
|
||||||
|
item.maxAge = maxAge
|
||||||
|
item.value = value
|
||||||
|
this[LENGTH] += len - item.length
|
||||||
|
item.length = len
|
||||||
|
this.get(key)
|
||||||
|
trim(this)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const hit = new Entry(key, value, len, now, maxAge)
|
||||||
|
|
||||||
|
// oversized objects fall out of cache automatically.
|
||||||
|
if (hit.length > this[MAX]) {
|
||||||
|
if (this[DISPOSE])
|
||||||
|
this[DISPOSE](key, value)
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
this[LENGTH] += hit.length
|
||||||
|
this[LRU_LIST].unshift(hit)
|
||||||
|
this[CACHE].set(key, this[LRU_LIST].head)
|
||||||
|
trim(this)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
has (key) {
|
||||||
|
if (!this[CACHE].has(key)) return false
|
||||||
|
const hit = this[CACHE].get(key).value
|
||||||
|
return !isStale(this, hit)
|
||||||
|
}
|
||||||
|
|
||||||
|
get (key) {
|
||||||
|
return get(this, key, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
peek (key) {
|
||||||
|
return get(this, key, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pop () {
|
||||||
|
const node = this[LRU_LIST].tail
|
||||||
|
if (!node)
|
||||||
|
return null
|
||||||
|
|
||||||
|
del(this, node)
|
||||||
|
return node.value
|
||||||
|
}
|
||||||
|
|
||||||
|
del (key) {
|
||||||
|
del(this, this[CACHE].get(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
load (arr) {
|
||||||
|
// reset the cache
|
||||||
|
this.reset()
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
// A previous serialized cache has the most recent items first
|
||||||
|
for (let l = arr.length - 1; l >= 0; l--) {
|
||||||
|
const hit = arr[l]
|
||||||
|
const expiresAt = hit.e || 0
|
||||||
|
if (expiresAt === 0)
|
||||||
|
// the item was created without expiration in a non aged cache
|
||||||
|
this.set(hit.k, hit.v)
|
||||||
|
else {
|
||||||
|
const maxAge = expiresAt - now
|
||||||
|
// dont add already expired items
|
||||||
|
if (maxAge > 0) {
|
||||||
|
this.set(hit.k, hit.v, maxAge)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
prune () {
|
||||||
|
this[CACHE].forEach((value, key) => get(this, key, false))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const get = (self, key, doUse) => {
|
||||||
|
const node = self[CACHE].get(key)
|
||||||
|
if (node) {
|
||||||
|
const hit = node.value
|
||||||
|
if (isStale(self, hit)) {
|
||||||
|
del(self, node)
|
||||||
|
if (!self[ALLOW_STALE])
|
||||||
|
return undefined
|
||||||
|
} else {
|
||||||
|
if (doUse) {
|
||||||
|
if (self[UPDATE_AGE_ON_GET])
|
||||||
|
node.value.now = Date.now()
|
||||||
|
self[LRU_LIST].unshiftNode(node)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hit.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isStale = (self, hit) => {
|
||||||
|
if (!hit || (!hit.maxAge && !self[MAX_AGE]))
|
||||||
|
return false
|
||||||
|
|
||||||
|
const diff = Date.now() - hit.now
|
||||||
|
return hit.maxAge ? diff > hit.maxAge
|
||||||
|
: self[MAX_AGE] && (diff > self[MAX_AGE])
|
||||||
|
}
|
||||||
|
|
||||||
|
const trim = self => {
|
||||||
|
if (self[LENGTH] > self[MAX]) {
|
||||||
|
for (let walker = self[LRU_LIST].tail;
|
||||||
|
self[LENGTH] > self[MAX] && walker !== null;) {
|
||||||
|
// We know that we're about to delete this one, and also
|
||||||
|
// what the next least recently used key will be, so just
|
||||||
|
// go ahead and set it now.
|
||||||
|
const prev = walker.prev
|
||||||
|
del(self, walker)
|
||||||
|
walker = prev
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const del = (self, node) => {
|
||||||
|
if (node) {
|
||||||
|
const hit = node.value
|
||||||
|
if (self[DISPOSE])
|
||||||
|
self[DISPOSE](hit.key, hit.value)
|
||||||
|
|
||||||
|
self[LENGTH] -= hit.length
|
||||||
|
self[CACHE].delete(hit.key)
|
||||||
|
self[LRU_LIST].removeNode(node)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Entry {
|
||||||
|
constructor (key, value, length, now, maxAge) {
|
||||||
|
this.key = key
|
||||||
|
this.value = value
|
||||||
|
this.length = length
|
||||||
|
this.now = now
|
||||||
|
this.maxAge = maxAge || 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const forEachStep = (self, fn, node, thisp) => {
|
||||||
|
let hit = node.value
|
||||||
|
if (isStale(self, hit)) {
|
||||||
|
del(self, node)
|
||||||
|
if (!self[ALLOW_STALE])
|
||||||
|
hit = undefined
|
||||||
|
}
|
||||||
|
if (hit)
|
||||||
|
fn.call(thisp, hit.value, hit.key, self)
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = LRUCache
|
@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"name": "lru-cache",
|
||||||
|
"description": "A cache object that deletes the least-recently-used items.",
|
||||||
|
"version": "6.0.0",
|
||||||
|
"author": "Isaac Z. Schlueter <i@izs.me>",
|
||||||
|
"keywords": [
|
||||||
|
"mru",
|
||||||
|
"lru",
|
||||||
|
"cache"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"test": "tap",
|
||||||
|
"snap": "tap",
|
||||||
|
"preversion": "npm test",
|
||||||
|
"postversion": "npm publish",
|
||||||
|
"prepublishOnly": "git push origin --follow-tags"
|
||||||
|
},
|
||||||
|
"main": "index.js",
|
||||||
|
"repository": "git://github.com/isaacs/node-lru-cache.git",
|
||||||
|
"devDependencies": {
|
||||||
|
"benchmark": "^2.1.4",
|
||||||
|
"tap": "^14.10.7"
|
||||||
|
},
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"yallist": "^4.0.0"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"index.js"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
The ISC License
|
||||||
|
|
||||||
|
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted, provided that the above
|
||||||
|
copyright notice and this permission notice appear in all copies.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||||
|
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||||
|
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||||
|
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||||
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||||
|
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
@ -0,0 +1,637 @@
|
|||||||
|
semver(1) -- The semantic versioner for npm
|
||||||
|
===========================================
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install semver
|
||||||
|
````
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
As a node module:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const semver = require('semver')
|
||||||
|
|
||||||
|
semver.valid('1.2.3') // '1.2.3'
|
||||||
|
semver.valid('a.b.c') // null
|
||||||
|
semver.clean(' =v1.2.3 ') // '1.2.3'
|
||||||
|
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
|
||||||
|
semver.gt('1.2.3', '9.8.7') // false
|
||||||
|
semver.lt('1.2.3', '9.8.7') // true
|
||||||
|
semver.minVersion('>=1.0.0') // '1.0.0'
|
||||||
|
semver.valid(semver.coerce('v2')) // '2.0.0'
|
||||||
|
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also just load the module for the function that you care about, if
|
||||||
|
you'd like to minimize your footprint.
|
||||||
|
|
||||||
|
```js
|
||||||
|
// load the whole API at once in a single object
|
||||||
|
const semver = require('semver')
|
||||||
|
|
||||||
|
// or just load the bits you need
|
||||||
|
// all of them listed here, just pick and choose what you want
|
||||||
|
|
||||||
|
// classes
|
||||||
|
const SemVer = require('semver/classes/semver')
|
||||||
|
const Comparator = require('semver/classes/comparator')
|
||||||
|
const Range = require('semver/classes/range')
|
||||||
|
|
||||||
|
// functions for working with versions
|
||||||
|
const semverParse = require('semver/functions/parse')
|
||||||
|
const semverValid = require('semver/functions/valid')
|
||||||
|
const semverClean = require('semver/functions/clean')
|
||||||
|
const semverInc = require('semver/functions/inc')
|
||||||
|
const semverDiff = require('semver/functions/diff')
|
||||||
|
const semverMajor = require('semver/functions/major')
|
||||||
|
const semverMinor = require('semver/functions/minor')
|
||||||
|
const semverPatch = require('semver/functions/patch')
|
||||||
|
const semverPrerelease = require('semver/functions/prerelease')
|
||||||
|
const semverCompare = require('semver/functions/compare')
|
||||||
|
const semverRcompare = require('semver/functions/rcompare')
|
||||||
|
const semverCompareLoose = require('semver/functions/compare-loose')
|
||||||
|
const semverCompareBuild = require('semver/functions/compare-build')
|
||||||
|
const semverSort = require('semver/functions/sort')
|
||||||
|
const semverRsort = require('semver/functions/rsort')
|
||||||
|
|
||||||
|
// low-level comparators between versions
|
||||||
|
const semverGt = require('semver/functions/gt')
|
||||||
|
const semverLt = require('semver/functions/lt')
|
||||||
|
const semverEq = require('semver/functions/eq')
|
||||||
|
const semverNeq = require('semver/functions/neq')
|
||||||
|
const semverGte = require('semver/functions/gte')
|
||||||
|
const semverLte = require('semver/functions/lte')
|
||||||
|
const semverCmp = require('semver/functions/cmp')
|
||||||
|
const semverCoerce = require('semver/functions/coerce')
|
||||||
|
|
||||||
|
// working with ranges
|
||||||
|
const semverSatisfies = require('semver/functions/satisfies')
|
||||||
|
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
|
||||||
|
const semverMinSatisfying = require('semver/ranges/min-satisfying')
|
||||||
|
const semverToComparators = require('semver/ranges/to-comparators')
|
||||||
|
const semverMinVersion = require('semver/ranges/min-version')
|
||||||
|
const semverValidRange = require('semver/ranges/valid')
|
||||||
|
const semverOutside = require('semver/ranges/outside')
|
||||||
|
const semverGtr = require('semver/ranges/gtr')
|
||||||
|
const semverLtr = require('semver/ranges/ltr')
|
||||||
|
const semverIntersects = require('semver/ranges/intersects')
|
||||||
|
const simplifyRange = require('semver/ranges/simplify')
|
||||||
|
const rangeSubset = require('semver/ranges/subset')
|
||||||
|
```
|
||||||
|
|
||||||
|
As a command-line utility:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ semver -h
|
||||||
|
|
||||||
|
A JavaScript implementation of the https://semver.org/ specification
|
||||||
|
Copyright Isaac Z. Schlueter
|
||||||
|
|
||||||
|
Usage: semver [options] <version> [<version> [...]]
|
||||||
|
Prints valid versions sorted by SemVer precedence
|
||||||
|
|
||||||
|
Options:
|
||||||
|
-r --range <range>
|
||||||
|
Print versions that match the specified range.
|
||||||
|
|
||||||
|
-i --increment [<level>]
|
||||||
|
Increment a version by the specified level. Level can
|
||||||
|
be one of: major, minor, patch, premajor, preminor,
|
||||||
|
prepatch, or prerelease. Default level is 'patch'.
|
||||||
|
Only one version may be specified.
|
||||||
|
|
||||||
|
--preid <identifier>
|
||||||
|
Identifier to be used to prefix premajor, preminor,
|
||||||
|
prepatch or prerelease version increments.
|
||||||
|
|
||||||
|
-l --loose
|
||||||
|
Interpret versions and ranges loosely
|
||||||
|
|
||||||
|
-n <0|1>
|
||||||
|
This is the base to be used for the prerelease identifier.
|
||||||
|
|
||||||
|
-p --include-prerelease
|
||||||
|
Always include prerelease versions in range matching
|
||||||
|
|
||||||
|
-c --coerce
|
||||||
|
Coerce a string into SemVer if possible
|
||||||
|
(does not imply --loose)
|
||||||
|
|
||||||
|
--rtl
|
||||||
|
Coerce version strings right to left
|
||||||
|
|
||||||
|
--ltr
|
||||||
|
Coerce version strings left to right (default)
|
||||||
|
|
||||||
|
Program exits successfully if any valid version satisfies
|
||||||
|
all supplied ranges, and prints all satisfying versions.
|
||||||
|
|
||||||
|
If no satisfying versions are found, then exits failure.
|
||||||
|
|
||||||
|
Versions are printed in ascending order, so supplying
|
||||||
|
multiple versions to the utility will just sort them.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
A "version" is described by the `v2.0.0` specification found at
|
||||||
|
<https://semver.org/>.
|
||||||
|
|
||||||
|
A leading `"="` or `"v"` character is stripped off and ignored.
|
||||||
|
|
||||||
|
## Ranges
|
||||||
|
|
||||||
|
A `version range` is a set of `comparators` which specify versions
|
||||||
|
that satisfy the range.
|
||||||
|
|
||||||
|
A `comparator` is composed of an `operator` and a `version`. The set
|
||||||
|
of primitive `operators` is:
|
||||||
|
|
||||||
|
* `<` Less than
|
||||||
|
* `<=` Less than or equal to
|
||||||
|
* `>` Greater than
|
||||||
|
* `>=` Greater than or equal to
|
||||||
|
* `=` Equal. If no operator is specified, then equality is assumed,
|
||||||
|
so this operator is optional, but MAY be included.
|
||||||
|
|
||||||
|
For example, the comparator `>=1.2.7` would match the versions
|
||||||
|
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
|
||||||
|
or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and
|
||||||
|
would match the versions `2.0.0` and `3.1.0`, but not the versions
|
||||||
|
`1.0.1` or `1.1.0`.
|
||||||
|
|
||||||
|
Comparators can be joined by whitespace to form a `comparator set`,
|
||||||
|
which is satisfied by the **intersection** of all of the comparators
|
||||||
|
it includes.
|
||||||
|
|
||||||
|
A range is composed of one or more comparator sets, joined by `||`. A
|
||||||
|
version matches a range if and only if every comparator in at least
|
||||||
|
one of the `||`-separated comparator sets is satisfied by the version.
|
||||||
|
|
||||||
|
For example, the range `>=1.2.7 <1.3.0` would match the versions
|
||||||
|
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
|
||||||
|
or `1.1.0`.
|
||||||
|
|
||||||
|
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
|
||||||
|
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
|
||||||
|
|
||||||
|
### Prerelease Tags
|
||||||
|
|
||||||
|
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
|
||||||
|
it will only be allowed to satisfy comparator sets if at least one
|
||||||
|
comparator with the same `[major, minor, patch]` tuple also has a
|
||||||
|
prerelease tag.
|
||||||
|
|
||||||
|
For example, the range `>1.2.3-alpha.3` would be allowed to match the
|
||||||
|
version `1.2.3-alpha.7`, but it would *not* be satisfied by
|
||||||
|
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
|
||||||
|
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
|
||||||
|
range only accepts prerelease tags on the `1.2.3` version. The
|
||||||
|
version `3.4.5` *would* satisfy the range, because it does not have a
|
||||||
|
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
|
||||||
|
|
||||||
|
The purpose for this behavior is twofold. First, prerelease versions
|
||||||
|
frequently are updated very quickly, and contain many breaking changes
|
||||||
|
that are (by the author's design) not yet fit for public consumption.
|
||||||
|
Therefore, by default, they are excluded from range matching
|
||||||
|
semantics.
|
||||||
|
|
||||||
|
Second, a user who has opted into using a prerelease version has
|
||||||
|
clearly indicated the intent to use *that specific* set of
|
||||||
|
alpha/beta/rc versions. By including a prerelease tag in the range,
|
||||||
|
the user is indicating that they are aware of the risk. However, it
|
||||||
|
is still not appropriate to assume that they have opted into taking a
|
||||||
|
similar risk on the *next* set of prerelease versions.
|
||||||
|
|
||||||
|
Note that this behavior can be suppressed (treating all prerelease
|
||||||
|
versions as if they were normal versions, for the purpose of range
|
||||||
|
matching) by setting the `includePrerelease` flag on the options
|
||||||
|
object to any
|
||||||
|
[functions](https://github.com/npm/node-semver#functions) that do
|
||||||
|
range matching.
|
||||||
|
|
||||||
|
#### Prerelease Identifiers
|
||||||
|
|
||||||
|
The method `.inc` takes an additional `identifier` string argument that
|
||||||
|
will append the value of the string as a prerelease identifier:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
semver.inc('1.2.3', 'prerelease', 'beta')
|
||||||
|
// '1.2.4-beta.0'
|
||||||
|
```
|
||||||
|
|
||||||
|
command-line example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ semver 1.2.3 -i prerelease --preid beta
|
||||||
|
1.2.4-beta.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Which then can be used to increment further:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ semver 1.2.4-beta.0 -i prerelease
|
||||||
|
1.2.4-beta.1
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Prerelease Identifier Base
|
||||||
|
|
||||||
|
The method `.inc` takes an optional parameter 'identifierBase' string
|
||||||
|
that will let you let your prerelease number as zero-based or one-based.
|
||||||
|
Set to `false` to omit the prerelease number altogether.
|
||||||
|
If you do not specify this parameter, it will default to zero-based.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
semver.inc('1.2.3', 'prerelease', 'beta', '1')
|
||||||
|
// '1.2.4-beta.1'
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
semver.inc('1.2.3', 'prerelease', 'beta', false)
|
||||||
|
// '1.2.4-beta'
|
||||||
|
```
|
||||||
|
|
||||||
|
command-line example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ semver 1.2.3 -i prerelease --preid beta -n 1
|
||||||
|
1.2.4-beta.1
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ semver 1.2.3 -i prerelease --preid beta -n false
|
||||||
|
1.2.4-beta
|
||||||
|
```
|
||||||
|
|
||||||
|
### Advanced Range Syntax
|
||||||
|
|
||||||
|
Advanced range syntax desugars to primitive comparators in
|
||||||
|
deterministic ways.
|
||||||
|
|
||||||
|
Advanced ranges may be combined in the same way as primitive
|
||||||
|
comparators using white space or `||`.
|
||||||
|
|
||||||
|
#### Hyphen Ranges `X.Y.Z - A.B.C`
|
||||||
|
|
||||||
|
Specifies an inclusive set.
|
||||||
|
|
||||||
|
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
|
||||||
|
|
||||||
|
If a partial version is provided as the first version in the inclusive
|
||||||
|
range, then the missing pieces are replaced with zeroes.
|
||||||
|
|
||||||
|
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
|
||||||
|
|
||||||
|
If a partial version is provided as the second version in the
|
||||||
|
inclusive range, then all versions that start with the supplied parts
|
||||||
|
of the tuple are accepted, but nothing that would be greater than the
|
||||||
|
provided tuple parts.
|
||||||
|
|
||||||
|
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
|
||||||
|
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
|
||||||
|
|
||||||
|
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
|
||||||
|
|
||||||
|
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
|
||||||
|
numeric values in the `[major, minor, patch]` tuple.
|
||||||
|
|
||||||
|
* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
|
||||||
|
`includePrerelease` is specified, in which case any version at all
|
||||||
|
satisfies)
|
||||||
|
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
|
||||||
|
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
|
||||||
|
|
||||||
|
A partial version range is treated as an X-Range, so the special
|
||||||
|
character is in fact optional.
|
||||||
|
|
||||||
|
* `""` (empty string) := `*` := `>=0.0.0`
|
||||||
|
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
|
||||||
|
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
|
||||||
|
|
||||||
|
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
|
||||||
|
|
||||||
|
Allows patch-level changes if a minor version is specified on the
|
||||||
|
comparator. Allows minor-level changes if not.
|
||||||
|
|
||||||
|
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
|
||||||
|
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
|
||||||
|
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
|
||||||
|
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
|
||||||
|
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
|
||||||
|
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
|
||||||
|
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
|
||||||
|
the `1.2.3` version will be allowed, if they are greater than or
|
||||||
|
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
||||||
|
`1.2.4-beta.2` would not, because it is a prerelease of a
|
||||||
|
different `[major, minor, patch]` tuple.
|
||||||
|
|
||||||
|
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
|
||||||
|
|
||||||
|
Allows changes that do not modify the left-most non-zero element in the
|
||||||
|
`[major, minor, patch]` tuple. In other words, this allows patch and
|
||||||
|
minor updates for versions `1.0.0` and above, patch updates for
|
||||||
|
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
|
||||||
|
|
||||||
|
Many authors treat a `0.x` version as if the `x` were the major
|
||||||
|
"breaking-change" indicator.
|
||||||
|
|
||||||
|
Caret ranges are ideal when an author may make breaking changes
|
||||||
|
between `0.2.4` and `0.3.0` releases, which is a common practice.
|
||||||
|
However, it presumes that there will *not* be breaking changes between
|
||||||
|
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
|
||||||
|
additive (but non-breaking), according to commonly observed practices.
|
||||||
|
|
||||||
|
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
|
||||||
|
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
|
||||||
|
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
|
||||||
|
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
|
||||||
|
the `1.2.3` version will be allowed, if they are greater than or
|
||||||
|
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
||||||
|
`1.2.4-beta.2` would not, because it is a prerelease of a
|
||||||
|
different `[major, minor, patch]` tuple.
|
||||||
|
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
|
||||||
|
`0.0.3` version *only* will be allowed, if they are greater than or
|
||||||
|
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
|
||||||
|
|
||||||
|
When parsing caret ranges, a missing `patch` value desugars to the
|
||||||
|
number `0`, but will allow flexibility within that value, even if the
|
||||||
|
major and minor versions are both `0`.
|
||||||
|
|
||||||
|
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
|
||||||
|
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
|
||||||
|
* `^0.0` := `>=0.0.0 <0.1.0-0`
|
||||||
|
|
||||||
|
A missing `minor` and `patch` values will desugar to zero, but also
|
||||||
|
allow flexibility within those values, even if the major version is
|
||||||
|
zero.
|
||||||
|
|
||||||
|
* `^1.x` := `>=1.0.0 <2.0.0-0`
|
||||||
|
* `^0.x` := `>=0.0.0 <1.0.0-0`
|
||||||
|
|
||||||
|
### Range Grammar
|
||||||
|
|
||||||
|
Putting all this together, here is a Backus-Naur grammar for ranges,
|
||||||
|
for the benefit of parser authors:
|
||||||
|
|
||||||
|
```bnf
|
||||||
|
range-set ::= range ( logical-or range ) *
|
||||||
|
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
|
||||||
|
range ::= hyphen | simple ( ' ' simple ) * | ''
|
||||||
|
hyphen ::= partial ' - ' partial
|
||||||
|
simple ::= primitive | partial | tilde | caret
|
||||||
|
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
|
||||||
|
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
|
||||||
|
xr ::= 'x' | 'X' | '*' | nr
|
||||||
|
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
|
||||||
|
tilde ::= '~' partial
|
||||||
|
caret ::= '^' partial
|
||||||
|
qualifier ::= ( '-' pre )? ( '+' build )?
|
||||||
|
pre ::= parts
|
||||||
|
build ::= parts
|
||||||
|
parts ::= part ( '.' part ) *
|
||||||
|
part ::= nr | [-0-9A-Za-z]+
|
||||||
|
```
|
||||||
|
|
||||||
|
## Functions
|
||||||
|
|
||||||
|
All methods and classes take a final `options` object argument. All
|
||||||
|
options in this object are `false` by default. The options supported
|
||||||
|
are:
|
||||||
|
|
||||||
|
- `loose` Be more forgiving about not-quite-valid semver strings.
|
||||||
|
(Any resulting output will always be 100% strict compliant, of
|
||||||
|
course.) For backwards compatibility reasons, if the `options`
|
||||||
|
argument is a boolean value instead of an object, it is interpreted
|
||||||
|
to be the `loose` param.
|
||||||
|
- `includePrerelease` Set to suppress the [default
|
||||||
|
behavior](https://github.com/npm/node-semver#prerelease-tags) of
|
||||||
|
excluding prerelease tagged versions from ranges unless they are
|
||||||
|
explicitly opted into.
|
||||||
|
|
||||||
|
Strict-mode Comparators and Ranges will be strict about the SemVer
|
||||||
|
strings that they parse.
|
||||||
|
|
||||||
|
* `valid(v)`: Return the parsed version, or null if it's not valid.
|
||||||
|
* `inc(v, release)`: Return the version incremented by the release
|
||||||
|
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
|
||||||
|
`prepatch`, or `prerelease`), or null if it's not valid
|
||||||
|
* `premajor` in one call will bump the version up to the next major
|
||||||
|
version and down to a prerelease of that major version.
|
||||||
|
`preminor`, and `prepatch` work the same way.
|
||||||
|
* If called from a non-prerelease version, the `prerelease` will work the
|
||||||
|
same as `prepatch`. It increments the patch version, then makes a
|
||||||
|
prerelease. If the input version is already a prerelease it simply
|
||||||
|
increments it.
|
||||||
|
* `prerelease(v)`: Returns an array of prerelease components, or null
|
||||||
|
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
|
||||||
|
* `major(v)`: Return the major version number.
|
||||||
|
* `minor(v)`: Return the minor version number.
|
||||||
|
* `patch(v)`: Return the patch version number.
|
||||||
|
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
|
||||||
|
or comparators intersect.
|
||||||
|
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
|
||||||
|
a `SemVer` object or `null`.
|
||||||
|
|
||||||
|
### Comparison
|
||||||
|
|
||||||
|
* `gt(v1, v2)`: `v1 > v2`
|
||||||
|
* `gte(v1, v2)`: `v1 >= v2`
|
||||||
|
* `lt(v1, v2)`: `v1 < v2`
|
||||||
|
* `lte(v1, v2)`: `v1 <= v2`
|
||||||
|
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
|
||||||
|
even if they're not the exact same string. You already know how to
|
||||||
|
compare strings.
|
||||||
|
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
|
||||||
|
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
|
||||||
|
the corresponding function above. `"==="` and `"!=="` do simple
|
||||||
|
string comparison, but are included for completeness. Throws if an
|
||||||
|
invalid comparison string is provided.
|
||||||
|
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
|
||||||
|
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
|
||||||
|
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
|
||||||
|
in descending order when passed to `Array.sort()`.
|
||||||
|
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
|
||||||
|
are equal. Sorts in ascending order if passed to `Array.sort()`.
|
||||||
|
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
|
||||||
|
* `diff(v1, v2)`: Returns difference between two versions by the release type
|
||||||
|
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
|
||||||
|
or null if the versions are the same.
|
||||||
|
|
||||||
|
### Comparators
|
||||||
|
|
||||||
|
* `intersects(comparator)`: Return true if the comparators intersect
|
||||||
|
|
||||||
|
### Ranges
|
||||||
|
|
||||||
|
* `validRange(range)`: Return the valid range or null if it's not valid
|
||||||
|
* `satisfies(version, range)`: Return true if the version satisfies the
|
||||||
|
range.
|
||||||
|
* `maxSatisfying(versions, range)`: Return the highest version in the list
|
||||||
|
that satisfies the range, or `null` if none of them do.
|
||||||
|
* `minSatisfying(versions, range)`: Return the lowest version in the list
|
||||||
|
that satisfies the range, or `null` if none of them do.
|
||||||
|
* `minVersion(range)`: Return the lowest version that can possibly match
|
||||||
|
the given range.
|
||||||
|
* `gtr(version, range)`: Return `true` if version is greater than all the
|
||||||
|
versions possible in the range.
|
||||||
|
* `ltr(version, range)`: Return `true` if version is less than all the
|
||||||
|
versions possible in the range.
|
||||||
|
* `outside(version, range, hilo)`: Return true if the version is outside
|
||||||
|
the bounds of the range in either the high or low direction. The
|
||||||
|
`hilo` argument must be either the string `'>'` or `'<'`. (This is
|
||||||
|
the function called by `gtr` and `ltr`.)
|
||||||
|
* `intersects(range)`: Return true if any of the ranges comparators intersect
|
||||||
|
* `simplifyRange(versions, range)`: Return a "simplified" range that
|
||||||
|
matches the same items in `versions` list as the range specified. Note
|
||||||
|
that it does *not* guarantee that it would match the same versions in all
|
||||||
|
cases, only for the set of versions provided. This is useful when
|
||||||
|
generating ranges by joining together multiple versions with `||`
|
||||||
|
programmatically, to provide the user with something a bit more
|
||||||
|
ergonomic. If the provided range is shorter in string-length than the
|
||||||
|
generated range, then that is returned.
|
||||||
|
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
|
||||||
|
entirely contained by the `superRange` range.
|
||||||
|
|
||||||
|
Note that, since ranges may be non-contiguous, a version might not be
|
||||||
|
greater than a range, less than a range, *or* satisfy a range! For
|
||||||
|
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
|
||||||
|
until `2.0.0`, so the version `1.2.10` would not be greater than the
|
||||||
|
range (because `2.0.1` satisfies, which is higher), nor less than the
|
||||||
|
range (since `1.2.8` satisfies, which is lower), and it also does not
|
||||||
|
satisfy the range.
|
||||||
|
|
||||||
|
If you want to know if a version satisfies or does not satisfy a
|
||||||
|
range, use the `satisfies(version, range)` function.
|
||||||
|
|
||||||
|
### Coercion
|
||||||
|
|
||||||
|
* `coerce(version, options)`: Coerces a string to semver if possible
|
||||||
|
|
||||||
|
This aims to provide a very forgiving translation of a non-semver string to
|
||||||
|
semver. It looks for the first digit in a string, and consumes all
|
||||||
|
remaining characters which satisfy at least a partial semver (e.g., `1`,
|
||||||
|
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
|
||||||
|
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
|
||||||
|
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
|
||||||
|
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
|
||||||
|
is not valid). The maximum length for any semver component considered for
|
||||||
|
coercion is 16 characters; longer components will be ignored
|
||||||
|
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
|
||||||
|
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
|
||||||
|
components are invalid (`9999999999999999.4.7.4` is likely invalid).
|
||||||
|
|
||||||
|
If the `options.rtl` flag is set, then `coerce` will return the right-most
|
||||||
|
coercible tuple that does not share an ending index with a longer coercible
|
||||||
|
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
|
||||||
|
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
|
||||||
|
any other overlapping SemVer tuple.
|
||||||
|
|
||||||
|
### Clean
|
||||||
|
|
||||||
|
* `clean(version)`: Clean a string to be a valid semver if possible
|
||||||
|
|
||||||
|
This will return a cleaned and trimmed semver version. If the provided
|
||||||
|
version is not valid a null will be returned. This does not work for
|
||||||
|
ranges.
|
||||||
|
|
||||||
|
ex.
|
||||||
|
* `s.clean(' = v 2.1.5foo')`: `null`
|
||||||
|
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
|
||||||
|
* `s.clean(' = v 2.1.5-foo')`: `null`
|
||||||
|
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
|
||||||
|
* `s.clean('=v2.1.5')`: `'2.1.5'`
|
||||||
|
* `s.clean(' =v2.1.5')`: `2.1.5`
|
||||||
|
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
|
||||||
|
* `s.clean('~1.0.0')`: `null`
|
||||||
|
|
||||||
|
## Constants
|
||||||
|
|
||||||
|
As a convenience, helper constants are exported to provide information about what `node-semver` supports:
|
||||||
|
|
||||||
|
### `RELEASE_TYPES`
|
||||||
|
|
||||||
|
- major
|
||||||
|
- premajor
|
||||||
|
- minor
|
||||||
|
- preminor
|
||||||
|
- patch
|
||||||
|
- prepatch
|
||||||
|
- prerelease
|
||||||
|
|
||||||
|
```
|
||||||
|
const semver = require('semver');
|
||||||
|
|
||||||
|
if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) {
|
||||||
|
console.log('This is a valid release type!');
|
||||||
|
} else {
|
||||||
|
console.warn('This is NOT a valid release type!');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `SEMVER_SPEC_VERSION`
|
||||||
|
|
||||||
|
2.0.0
|
||||||
|
|
||||||
|
```
|
||||||
|
const semver = require('semver');
|
||||||
|
|
||||||
|
console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Exported Modules
|
||||||
|
|
||||||
|
<!--
|
||||||
|
TODO: Make sure that all of these items are documented (classes aren't,
|
||||||
|
eg), and then pull the module name into the documentation for that specific
|
||||||
|
thing.
|
||||||
|
-->
|
||||||
|
|
||||||
|
You may pull in just the part of this semver utility that you need, if you
|
||||||
|
are sensitive to packing and tree-shaking concerns. The main
|
||||||
|
`require('semver')` export uses getter functions to lazily load the parts
|
||||||
|
of the API that are used.
|
||||||
|
|
||||||
|
The following modules are available:
|
||||||
|
|
||||||
|
* `require('semver')`
|
||||||
|
* `require('semver/classes')`
|
||||||
|
* `require('semver/classes/comparator')`
|
||||||
|
* `require('semver/classes/range')`
|
||||||
|
* `require('semver/classes/semver')`
|
||||||
|
* `require('semver/functions/clean')`
|
||||||
|
* `require('semver/functions/cmp')`
|
||||||
|
* `require('semver/functions/coerce')`
|
||||||
|
* `require('semver/functions/compare')`
|
||||||
|
* `require('semver/functions/compare-build')`
|
||||||
|
* `require('semver/functions/compare-loose')`
|
||||||
|
* `require('semver/functions/diff')`
|
||||||
|
* `require('semver/functions/eq')`
|
||||||
|
* `require('semver/functions/gt')`
|
||||||
|
* `require('semver/functions/gte')`
|
||||||
|
* `require('semver/functions/inc')`
|
||||||
|
* `require('semver/functions/lt')`
|
||||||
|
* `require('semver/functions/lte')`
|
||||||
|
* `require('semver/functions/major')`
|
||||||
|
* `require('semver/functions/minor')`
|
||||||
|
* `require('semver/functions/neq')`
|
||||||
|
* `require('semver/functions/parse')`
|
||||||
|
* `require('semver/functions/patch')`
|
||||||
|
* `require('semver/functions/prerelease')`
|
||||||
|
* `require('semver/functions/rcompare')`
|
||||||
|
* `require('semver/functions/rsort')`
|
||||||
|
* `require('semver/functions/satisfies')`
|
||||||
|
* `require('semver/functions/sort')`
|
||||||
|
* `require('semver/functions/valid')`
|
||||||
|
* `require('semver/ranges/gtr')`
|
||||||
|
* `require('semver/ranges/intersects')`
|
||||||
|
* `require('semver/ranges/ltr')`
|
||||||
|
* `require('semver/ranges/max-satisfying')`
|
||||||
|
* `require('semver/ranges/min-satisfying')`
|
||||||
|
* `require('semver/ranges/min-version')`
|
||||||
|
* `require('semver/ranges/outside')`
|
||||||
|
* `require('semver/ranges/to-comparators')`
|
||||||
|
* `require('semver/ranges/valid')`
|
||||||
|
|
@ -0,0 +1,197 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Standalone semver comparison program.
|
||||||
|
// Exits successfully and prints matching version(s) if
|
||||||
|
// any supplied version is valid and passes all tests.
|
||||||
|
|
||||||
|
const argv = process.argv.slice(2)
|
||||||
|
|
||||||
|
let versions = []
|
||||||
|
|
||||||
|
const range = []
|
||||||
|
|
||||||
|
let inc = null
|
||||||
|
|
||||||
|
const version = require('../package.json').version
|
||||||
|
|
||||||
|
let loose = false
|
||||||
|
|
||||||
|
let includePrerelease = false
|
||||||
|
|
||||||
|
let coerce = false
|
||||||
|
|
||||||
|
let rtl = false
|
||||||
|
|
||||||
|
let identifier
|
||||||
|
|
||||||
|
let identifierBase
|
||||||
|
|
||||||
|
const semver = require('../')
|
||||||
|
const parseOptions = require('../internal/parse-options')
|
||||||
|
|
||||||
|
let reverse = false
|
||||||
|
|
||||||
|
let options = {}
|
||||||
|
|
||||||
|
const main = () => {
|
||||||
|
if (!argv.length) {
|
||||||
|
return help()
|
||||||
|
}
|
||||||
|
while (argv.length) {
|
||||||
|
let a = argv.shift()
|
||||||
|
const indexOfEqualSign = a.indexOf('=')
|
||||||
|
if (indexOfEqualSign !== -1) {
|
||||||
|
const value = a.slice(indexOfEqualSign + 1)
|
||||||
|
a = a.slice(0, indexOfEqualSign)
|
||||||
|
argv.unshift(value)
|
||||||
|
}
|
||||||
|
switch (a) {
|
||||||
|
case '-rv': case '-rev': case '--rev': case '--reverse':
|
||||||
|
reverse = true
|
||||||
|
break
|
||||||
|
case '-l': case '--loose':
|
||||||
|
loose = true
|
||||||
|
break
|
||||||
|
case '-p': case '--include-prerelease':
|
||||||
|
includePrerelease = true
|
||||||
|
break
|
||||||
|
case '-v': case '--version':
|
||||||
|
versions.push(argv.shift())
|
||||||
|
break
|
||||||
|
case '-i': case '--inc': case '--increment':
|
||||||
|
switch (argv[0]) {
|
||||||
|
case 'major': case 'minor': case 'patch': case 'prerelease':
|
||||||
|
case 'premajor': case 'preminor': case 'prepatch':
|
||||||
|
inc = argv.shift()
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
inc = 'patch'
|
||||||
|
break
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case '--preid':
|
||||||
|
identifier = argv.shift()
|
||||||
|
break
|
||||||
|
case '-r': case '--range':
|
||||||
|
range.push(argv.shift())
|
||||||
|
break
|
||||||
|
case '-n':
|
||||||
|
identifierBase = argv.shift()
|
||||||
|
if (identifierBase === 'false') {
|
||||||
|
identifierBase = false
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case '-c': case '--coerce':
|
||||||
|
coerce = true
|
||||||
|
break
|
||||||
|
case '--rtl':
|
||||||
|
rtl = true
|
||||||
|
break
|
||||||
|
case '--ltr':
|
||||||
|
rtl = false
|
||||||
|
break
|
||||||
|
case '-h': case '--help': case '-?':
|
||||||
|
return help()
|
||||||
|
default:
|
||||||
|
versions.push(a)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
options = parseOptions({ loose, includePrerelease, rtl })
|
||||||
|
|
||||||
|
versions = versions.map((v) => {
|
||||||
|
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
|
||||||
|
}).filter((v) => {
|
||||||
|
return semver.valid(v)
|
||||||
|
})
|
||||||
|
if (!versions.length) {
|
||||||
|
return fail()
|
||||||
|
}
|
||||||
|
if (inc && (versions.length !== 1 || range.length)) {
|
||||||
|
return failInc()
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0, l = range.length; i < l; i++) {
|
||||||
|
versions = versions.filter((v) => {
|
||||||
|
return semver.satisfies(v, range[i], options)
|
||||||
|
})
|
||||||
|
if (!versions.length) {
|
||||||
|
return fail()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return success(versions)
|
||||||
|
}
|
||||||
|
|
||||||
|
const failInc = () => {
|
||||||
|
console.error('--inc can only be used on a single version with no range')
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
|
||||||
|
const fail = () => process.exit(1)
|
||||||
|
|
||||||
|
const success = () => {
|
||||||
|
const compare = reverse ? 'rcompare' : 'compare'
|
||||||
|
versions.sort((a, b) => {
|
||||||
|
return semver[compare](a, b, options)
|
||||||
|
}).map((v) => {
|
||||||
|
return semver.clean(v, options)
|
||||||
|
}).map((v) => {
|
||||||
|
return inc ? semver.inc(v, inc, options, identifier, identifierBase) : v
|
||||||
|
}).forEach((v, i, _) => {
|
||||||
|
console.log(v)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const help = () => console.log(
|
||||||
|
`SemVer ${version}
|
||||||
|
|
||||||
|
A JavaScript implementation of the https://semver.org/ specification
|
||||||
|
Copyright Isaac Z. Schlueter
|
||||||
|
|
||||||
|
Usage: semver [options] <version> [<version> [...]]
|
||||||
|
Prints valid versions sorted by SemVer precedence
|
||||||
|
|
||||||
|
Options:
|
||||||
|
-r --range <range>
|
||||||
|
Print versions that match the specified range.
|
||||||
|
|
||||||
|
-i --increment [<level>]
|
||||||
|
Increment a version by the specified level. Level can
|
||||||
|
be one of: major, minor, patch, premajor, preminor,
|
||||||
|
prepatch, or prerelease. Default level is 'patch'.
|
||||||
|
Only one version may be specified.
|
||||||
|
|
||||||
|
--preid <identifier>
|
||||||
|
Identifier to be used to prefix premajor, preminor,
|
||||||
|
prepatch or prerelease version increments.
|
||||||
|
|
||||||
|
-l --loose
|
||||||
|
Interpret versions and ranges loosely
|
||||||
|
|
||||||
|
-p --include-prerelease
|
||||||
|
Always include prerelease versions in range matching
|
||||||
|
|
||||||
|
-c --coerce
|
||||||
|
Coerce a string into SemVer if possible
|
||||||
|
(does not imply --loose)
|
||||||
|
|
||||||
|
--rtl
|
||||||
|
Coerce version strings right to left
|
||||||
|
|
||||||
|
--ltr
|
||||||
|
Coerce version strings left to right (default)
|
||||||
|
|
||||||
|
-n <base>
|
||||||
|
Base number to be used for the prerelease identifier.
|
||||||
|
Can be either 0 or 1, or false to omit the number altogether.
|
||||||
|
Defaults to 0.
|
||||||
|
|
||||||
|
Program exits successfully if any valid version satisfies
|
||||||
|
all supplied ranges, and prints all satisfying versions.
|
||||||
|
|
||||||
|
If no satisfying versions are found, then exits failure.
|
||||||
|
|
||||||
|
Versions are printed in ascending order, so supplying
|
||||||
|
multiple versions to the utility will just sort them.`)
|
||||||
|
|
||||||
|
main()
|
@ -0,0 +1,141 @@
|
|||||||
|
const ANY = Symbol('SemVer ANY')
|
||||||
|
// hoisted class for cyclic dependency
|
||||||
|
class Comparator {
|
||||||
|
static get ANY () {
|
||||||
|
return ANY
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor (comp, options) {
|
||||||
|
options = parseOptions(options)
|
||||||
|
|
||||||
|
if (comp instanceof Comparator) {
|
||||||
|
if (comp.loose === !!options.loose) {
|
||||||
|
return comp
|
||||||
|
} else {
|
||||||
|
comp = comp.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
comp = comp.trim().split(/\s+/).join(' ')
|
||||||
|
debug('comparator', comp, options)
|
||||||
|
this.options = options
|
||||||
|
this.loose = !!options.loose
|
||||||
|
this.parse(comp)
|
||||||
|
|
||||||
|
if (this.semver === ANY) {
|
||||||
|
this.value = ''
|
||||||
|
} else {
|
||||||
|
this.value = this.operator + this.semver.version
|
||||||
|
}
|
||||||
|
|
||||||
|
debug('comp', this)
|
||||||
|
}
|
||||||
|
|
||||||
|
parse (comp) {
|
||||||
|
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
|
||||||
|
const m = comp.match(r)
|
||||||
|
|
||||||
|
if (!m) {
|
||||||
|
throw new TypeError(`Invalid comparator: ${comp}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.operator = m[1] !== undefined ? m[1] : ''
|
||||||
|
if (this.operator === '=') {
|
||||||
|
this.operator = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// if it literally is just '>' or '' then allow anything.
|
||||||
|
if (!m[2]) {
|
||||||
|
this.semver = ANY
|
||||||
|
} else {
|
||||||
|
this.semver = new SemVer(m[2], this.options.loose)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toString () {
|
||||||
|
return this.value
|
||||||
|
}
|
||||||
|
|
||||||
|
test (version) {
|
||||||
|
debug('Comparator.test', version, this.options.loose)
|
||||||
|
|
||||||
|
if (this.semver === ANY || version === ANY) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof version === 'string') {
|
||||||
|
try {
|
||||||
|
version = new SemVer(version, this.options)
|
||||||
|
} catch (er) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return cmp(version, this.operator, this.semver, this.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
intersects (comp, options) {
|
||||||
|
if (!(comp instanceof Comparator)) {
|
||||||
|
throw new TypeError('a Comparator is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.operator === '') {
|
||||||
|
if (this.value === '') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return new Range(comp.value, options).test(this.value)
|
||||||
|
} else if (comp.operator === '') {
|
||||||
|
if (comp.value === '') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return new Range(this.value, options).test(comp.semver)
|
||||||
|
}
|
||||||
|
|
||||||
|
options = parseOptions(options)
|
||||||
|
|
||||||
|
// Special cases where nothing can possibly be lower
|
||||||
|
if (options.includePrerelease &&
|
||||||
|
(this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (!options.includePrerelease &&
|
||||||
|
(this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same direction increasing (> or >=)
|
||||||
|
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Same direction decreasing (< or <=)
|
||||||
|
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// same SemVer and both sides are inclusive (<= or >=)
|
||||||
|
if (
|
||||||
|
(this.semver.version === comp.semver.version) &&
|
||||||
|
this.operator.includes('=') && comp.operator.includes('=')) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// opposite directions less than
|
||||||
|
if (cmp(this.semver, '<', comp.semver, options) &&
|
||||||
|
this.operator.startsWith('>') && comp.operator.startsWith('<')) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// opposite directions greater than
|
||||||
|
if (cmp(this.semver, '>', comp.semver, options) &&
|
||||||
|
this.operator.startsWith('<') && comp.operator.startsWith('>')) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Comparator
|
||||||
|
|
||||||
|
const parseOptions = require('../internal/parse-options')
|
||||||
|
const { safeRe: re, t } = require('../internal/re')
|
||||||
|
const cmp = require('../functions/cmp')
|
||||||
|
const debug = require('../internal/debug')
|
||||||
|
const SemVer = require('./semver')
|
||||||
|
const Range = require('./range')
|
@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
SemVer: require('./semver.js'),
|
||||||
|
Range: require('./range.js'),
|
||||||
|
Comparator: require('./comparator.js'),
|
||||||
|
}
|
@ -0,0 +1,539 @@
|
|||||||
|
// hoisted class for cyclic dependency
|
||||||
|
class Range {
|
||||||
|
constructor (range, options) {
|
||||||
|
options = parseOptions(options)
|
||||||
|
|
||||||
|
if (range instanceof Range) {
|
||||||
|
if (
|
||||||
|
range.loose === !!options.loose &&
|
||||||
|
range.includePrerelease === !!options.includePrerelease
|
||||||
|
) {
|
||||||
|
return range
|
||||||
|
} else {
|
||||||
|
return new Range(range.raw, options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (range instanceof Comparator) {
|
||||||
|
// just put it in the set and return
|
||||||
|
this.raw = range.value
|
||||||
|
this.set = [[range]]
|
||||||
|
this.format()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
this.options = options
|
||||||
|
this.loose = !!options.loose
|
||||||
|
this.includePrerelease = !!options.includePrerelease
|
||||||
|
|
||||||
|
// First reduce all whitespace as much as possible so we do not have to rely
|
||||||
|
// on potentially slow regexes like \s*. This is then stored and used for
|
||||||
|
// future error messages as well.
|
||||||
|
this.raw = range
|
||||||
|
.trim()
|
||||||
|
.split(/\s+/)
|
||||||
|
.join(' ')
|
||||||
|
|
||||||
|
// First, split on ||
|
||||||
|
this.set = this.raw
|
||||||
|
.split('||')
|
||||||
|
// map the range to a 2d array of comparators
|
||||||
|
.map(r => this.parseRange(r))
|
||||||
|
// throw out any comparator lists that are empty
|
||||||
|
// this generally means that it was not a valid range, which is allowed
|
||||||
|
// in loose mode, but will still throw if the WHOLE range is invalid.
|
||||||
|
.filter(c => c.length)
|
||||||
|
|
||||||
|
if (!this.set.length) {
|
||||||
|
throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// if we have any that are not the null set, throw out null sets.
|
||||||
|
if (this.set.length > 1) {
|
||||||
|
// keep the first one, in case they're all null sets
|
||||||
|
const first = this.set[0]
|
||||||
|
this.set = this.set.filter(c => !isNullSet(c[0]))
|
||||||
|
if (this.set.length === 0) {
|
||||||
|
this.set = [first]
|
||||||
|
} else if (this.set.length > 1) {
|
||||||
|
// if we have any that are *, then the range is just *
|
||||||
|
for (const c of this.set) {
|
||||||
|
if (c.length === 1 && isAny(c[0])) {
|
||||||
|
this.set = [c]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.format()
|
||||||
|
}
|
||||||
|
|
||||||
|
format () {
|
||||||
|
this.range = this.set
|
||||||
|
.map((comps) => comps.join(' ').trim())
|
||||||
|
.join('||')
|
||||||
|
.trim()
|
||||||
|
return this.range
|
||||||
|
}
|
||||||
|
|
||||||
|
toString () {
|
||||||
|
return this.range
|
||||||
|
}
|
||||||
|
|
||||||
|
parseRange (range) {
|
||||||
|
// memoize range parsing for performance.
|
||||||
|
// this is a very hot path, and fully deterministic.
|
||||||
|
const memoOpts =
|
||||||
|
(this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
|
||||||
|
(this.options.loose && FLAG_LOOSE)
|
||||||
|
const memoKey = memoOpts + ':' + range
|
||||||
|
const cached = cache.get(memoKey)
|
||||||
|
if (cached) {
|
||||||
|
return cached
|
||||||
|
}
|
||||||
|
|
||||||
|
const loose = this.options.loose
|
||||||
|
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
|
||||||
|
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
|
||||||
|
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
|
||||||
|
debug('hyphen replace', range)
|
||||||
|
|
||||||
|
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
|
||||||
|
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
|
||||||
|
debug('comparator trim', range)
|
||||||
|
|
||||||
|
// `~ 1.2.3` => `~1.2.3`
|
||||||
|
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
|
||||||
|
debug('tilde trim', range)
|
||||||
|
|
||||||
|
// `^ 1.2.3` => `^1.2.3`
|
||||||
|
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
|
||||||
|
debug('caret trim', range)
|
||||||
|
|
||||||
|
// At this point, the range is completely trimmed and
|
||||||
|
// ready to be split into comparators.
|
||||||
|
|
||||||
|
let rangeList = range
|
||||||
|
.split(' ')
|
||||||
|
.map(comp => parseComparator(comp, this.options))
|
||||||
|
.join(' ')
|
||||||
|
.split(/\s+/)
|
||||||
|
// >=0.0.0 is equivalent to *
|
||||||
|
.map(comp => replaceGTE0(comp, this.options))
|
||||||
|
|
||||||
|
if (loose) {
|
||||||
|
// in loose mode, throw out any that are not valid comparators
|
||||||
|
rangeList = rangeList.filter(comp => {
|
||||||
|
debug('loose invalid filter', comp, this.options)
|
||||||
|
return !!comp.match(re[t.COMPARATORLOOSE])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
debug('range list', rangeList)
|
||||||
|
|
||||||
|
// if any comparators are the null set, then replace with JUST null set
|
||||||
|
// if more than one comparator, remove any * comparators
|
||||||
|
// also, don't include the same comparator more than once
|
||||||
|
const rangeMap = new Map()
|
||||||
|
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
|
||||||
|
for (const comp of comparators) {
|
||||||
|
if (isNullSet(comp)) {
|
||||||
|
return [comp]
|
||||||
|
}
|
||||||
|
rangeMap.set(comp.value, comp)
|
||||||
|
}
|
||||||
|
if (rangeMap.size > 1 && rangeMap.has('')) {
|
||||||
|
rangeMap.delete('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = [...rangeMap.values()]
|
||||||
|
cache.set(memoKey, result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
intersects (range, options) {
|
||||||
|
if (!(range instanceof Range)) {
|
||||||
|
throw new TypeError('a Range is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.set.some((thisComparators) => {
|
||||||
|
return (
|
||||||
|
isSatisfiable(thisComparators, options) &&
|
||||||
|
range.set.some((rangeComparators) => {
|
||||||
|
return (
|
||||||
|
isSatisfiable(rangeComparators, options) &&
|
||||||
|
thisComparators.every((thisComparator) => {
|
||||||
|
return rangeComparators.every((rangeComparator) => {
|
||||||
|
return thisComparator.intersects(rangeComparator, options)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// if ANY of the sets match ALL of its comparators, then pass
|
||||||
|
test (version) {
|
||||||
|
if (!version) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof version === 'string') {
|
||||||
|
try {
|
||||||
|
version = new SemVer(version, this.options)
|
||||||
|
} catch (er) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0; i < this.set.length; i++) {
|
||||||
|
if (testSet(this.set[i], version, this.options)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Range
|
||||||
|
|
||||||
|
const LRU = require('lru-cache')
|
||||||
|
const cache = new LRU({ max: 1000 })
|
||||||
|
|
||||||
|
const parseOptions = require('../internal/parse-options')
|
||||||
|
const Comparator = require('./comparator')
|
||||||
|
const debug = require('../internal/debug')
|
||||||
|
const SemVer = require('./semver')
|
||||||
|
const {
|
||||||
|
safeRe: re,
|
||||||
|
t,
|
||||||
|
comparatorTrimReplace,
|
||||||
|
tildeTrimReplace,
|
||||||
|
caretTrimReplace,
|
||||||
|
} = require('../internal/re')
|
||||||
|
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')
|
||||||
|
|
||||||
|
const isNullSet = c => c.value === '<0.0.0-0'
|
||||||
|
const isAny = c => c.value === ''
|
||||||
|
|
||||||
|
// take a set of comparators and determine whether there
|
||||||
|
// exists a version which can satisfy it
|
||||||
|
const isSatisfiable = (comparators, options) => {
|
||||||
|
let result = true
|
||||||
|
const remainingComparators = comparators.slice()
|
||||||
|
let testComparator = remainingComparators.pop()
|
||||||
|
|
||||||
|
while (result && remainingComparators.length) {
|
||||||
|
result = remainingComparators.every((otherComparator) => {
|
||||||
|
return testComparator.intersects(otherComparator, options)
|
||||||
|
})
|
||||||
|
|
||||||
|
testComparator = remainingComparators.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// comprised of xranges, tildes, stars, and gtlt's at this point.
|
||||||
|
// already replaced the hyphen ranges
|
||||||
|
// turn into a set of JUST comparators.
|
||||||
|
const parseComparator = (comp, options) => {
|
||||||
|
debug('comp', comp, options)
|
||||||
|
comp = replaceCarets(comp, options)
|
||||||
|
debug('caret', comp)
|
||||||
|
comp = replaceTildes(comp, options)
|
||||||
|
debug('tildes', comp)
|
||||||
|
comp = replaceXRanges(comp, options)
|
||||||
|
debug('xrange', comp)
|
||||||
|
comp = replaceStars(comp, options)
|
||||||
|
debug('stars', comp)
|
||||||
|
return comp
|
||||||
|
}
|
||||||
|
|
||||||
|
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
|
||||||
|
|
||||||
|
// ~, ~> --> * (any, kinda silly)
|
||||||
|
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
|
||||||
|
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
|
||||||
|
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
|
||||||
|
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
|
||||||
|
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
|
||||||
|
// ~0.0.1 --> >=0.0.1 <0.1.0-0
|
||||||
|
const replaceTildes = (comp, options) => {
|
||||||
|
return comp
|
||||||
|
.trim()
|
||||||
|
.split(/\s+/)
|
||||||
|
.map((c) => replaceTilde(c, options))
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
const replaceTilde = (comp, options) => {
|
||||||
|
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
|
||||||
|
return comp.replace(r, (_, M, m, p, pr) => {
|
||||||
|
debug('tilde', comp, _, M, m, p, pr)
|
||||||
|
let ret
|
||||||
|
|
||||||
|
if (isX(M)) {
|
||||||
|
ret = ''
|
||||||
|
} else if (isX(m)) {
|
||||||
|
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
|
||||||
|
} else if (isX(p)) {
|
||||||
|
// ~1.2 == >=1.2.0 <1.3.0-0
|
||||||
|
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
|
||||||
|
} else if (pr) {
|
||||||
|
debug('replaceTilde pr', pr)
|
||||||
|
ret = `>=${M}.${m}.${p}-${pr
|
||||||
|
} <${M}.${+m + 1}.0-0`
|
||||||
|
} else {
|
||||||
|
// ~1.2.3 == >=1.2.3 <1.3.0-0
|
||||||
|
ret = `>=${M}.${m}.${p
|
||||||
|
} <${M}.${+m + 1}.0-0`
|
||||||
|
}
|
||||||
|
|
||||||
|
debug('tilde return', ret)
|
||||||
|
return ret
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ^ --> * (any, kinda silly)
|
||||||
|
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
|
||||||
|
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
|
||||||
|
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
|
||||||
|
// ^1.2.3 --> >=1.2.3 <2.0.0-0
|
||||||
|
// ^1.2.0 --> >=1.2.0 <2.0.0-0
|
||||||
|
// ^0.0.1 --> >=0.0.1 <0.0.2-0
|
||||||
|
// ^0.1.0 --> >=0.1.0 <0.2.0-0
|
||||||
|
const replaceCarets = (comp, options) => {
|
||||||
|
return comp
|
||||||
|
.trim()
|
||||||
|
.split(/\s+/)
|
||||||
|
.map((c) => replaceCaret(c, options))
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
const replaceCaret = (comp, options) => {
|
||||||
|
debug('caret', comp, options)
|
||||||
|
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
|
||||||
|
const z = options.includePrerelease ? '-0' : ''
|
||||||
|
return comp.replace(r, (_, M, m, p, pr) => {
|
||||||
|
debug('caret', comp, _, M, m, p, pr)
|
||||||
|
let ret
|
||||||
|
|
||||||
|
if (isX(M)) {
|
||||||
|
ret = ''
|
||||||
|
} else if (isX(m)) {
|
||||||
|
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
|
||||||
|
} else if (isX(p)) {
|
||||||
|
if (M === '0') {
|
||||||
|
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
|
||||||
|
} else {
|
||||||
|
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
|
||||||
|
}
|
||||||
|
} else if (pr) {
|
||||||
|
debug('replaceCaret pr', pr)
|
||||||
|
if (M === '0') {
|
||||||
|
if (m === '0') {
|
||||||
|
ret = `>=${M}.${m}.${p}-${pr
|
||||||
|
} <${M}.${m}.${+p + 1}-0`
|
||||||
|
} else {
|
||||||
|
ret = `>=${M}.${m}.${p}-${pr
|
||||||
|
} <${M}.${+m + 1}.0-0`
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ret = `>=${M}.${m}.${p}-${pr
|
||||||
|
} <${+M + 1}.0.0-0`
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
debug('no pr')
|
||||||
|
if (M === '0') {
|
||||||
|
if (m === '0') {
|
||||||
|
ret = `>=${M}.${m}.${p
|
||||||
|
}${z} <${M}.${m}.${+p + 1}-0`
|
||||||
|
} else {
|
||||||
|
ret = `>=${M}.${m}.${p
|
||||||
|
}${z} <${M}.${+m + 1}.0-0`
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ret = `>=${M}.${m}.${p
|
||||||
|
} <${+M + 1}.0.0-0`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
debug('caret return', ret)
|
||||||
|
return ret
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const replaceXRanges = (comp, options) => {
|
||||||
|
debug('replaceXRanges', comp, options)
|
||||||
|
return comp
|
||||||
|
.split(/\s+/)
|
||||||
|
.map((c) => replaceXRange(c, options))
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
const replaceXRange = (comp, options) => {
|
||||||
|
comp = comp.trim()
|
||||||
|
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
|
||||||
|
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
|
||||||
|
debug('xRange', comp, ret, gtlt, M, m, p, pr)
|
||||||
|
const xM = isX(M)
|
||||||
|
const xm = xM || isX(m)
|
||||||
|
const xp = xm || isX(p)
|
||||||
|
const anyX = xp
|
||||||
|
|
||||||
|
if (gtlt === '=' && anyX) {
|
||||||
|
gtlt = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// if we're including prereleases in the match, then we need
|
||||||
|
// to fix this to -0, the lowest possible prerelease value
|
||||||
|
pr = options.includePrerelease ? '-0' : ''
|
||||||
|
|
||||||
|
if (xM) {
|
||||||
|
if (gtlt === '>' || gtlt === '<') {
|
||||||
|
// nothing is allowed
|
||||||
|
ret = '<0.0.0-0'
|
||||||
|
} else {
|
||||||
|
// nothing is forbidden
|
||||||
|
ret = '*'
|
||||||
|
}
|
||||||
|
} else if (gtlt && anyX) {
|
||||||
|
// we know patch is an x, because we have any x at all.
|
||||||
|
// replace X with 0
|
||||||
|
if (xm) {
|
||||||
|
m = 0
|
||||||
|
}
|
||||||
|
p = 0
|
||||||
|
|
||||||
|
if (gtlt === '>') {
|
||||||
|
// >1 => >=2.0.0
|
||||||
|
// >1.2 => >=1.3.0
|
||||||
|
gtlt = '>='
|
||||||
|
if (xm) {
|
||||||
|
M = +M + 1
|
||||||
|
m = 0
|
||||||
|
p = 0
|
||||||
|
} else {
|
||||||
|
m = +m + 1
|
||||||
|
p = 0
|
||||||
|
}
|
||||||
|
} else if (gtlt === '<=') {
|
||||||
|
// <=0.7.x is actually <0.8.0, since any 0.7.x should
|
||||||
|
// pass. Similarly, <=7.x is actually <8.0.0, etc.
|
||||||
|
gtlt = '<'
|
||||||
|
if (xm) {
|
||||||
|
M = +M + 1
|
||||||
|
} else {
|
||||||
|
m = +m + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (gtlt === '<') {
|
||||||
|
pr = '-0'
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = `${gtlt + M}.${m}.${p}${pr}`
|
||||||
|
} else if (xm) {
|
||||||
|
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
|
||||||
|
} else if (xp) {
|
||||||
|
ret = `>=${M}.${m}.0${pr
|
||||||
|
} <${M}.${+m + 1}.0-0`
|
||||||
|
}
|
||||||
|
|
||||||
|
debug('xRange return', ret)
|
||||||
|
|
||||||
|
return ret
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Because * is AND-ed with everything else in the comparator,
|
||||||
|
// and '' means "any version", just remove the *s entirely.
|
||||||
|
const replaceStars = (comp, options) => {
|
||||||
|
debug('replaceStars', comp, options)
|
||||||
|
// Looseness is ignored here. star is always as loose as it gets!
|
||||||
|
return comp
|
||||||
|
.trim()
|
||||||
|
.replace(re[t.STAR], '')
|
||||||
|
}
|
||||||
|
|
||||||
|
const replaceGTE0 = (comp, options) => {
|
||||||
|
debug('replaceGTE0', comp, options)
|
||||||
|
return comp
|
||||||
|
.trim()
|
||||||
|
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
|
||||||
|
}
|
||||||
|
|
||||||
|
// This function is passed to string.replace(re[t.HYPHENRANGE])
|
||||||
|
// M, m, patch, prerelease, build
|
||||||
|
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
|
||||||
|
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
|
||||||
|
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
|
||||||
|
const hyphenReplace = incPr => ($0,
|
||||||
|
from, fM, fm, fp, fpr, fb,
|
||||||
|
to, tM, tm, tp, tpr, tb) => {
|
||||||
|
if (isX(fM)) {
|
||||||
|
from = ''
|
||||||
|
} else if (isX(fm)) {
|
||||||
|
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
|
||||||
|
} else if (isX(fp)) {
|
||||||
|
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
|
||||||
|
} else if (fpr) {
|
||||||
|
from = `>=${from}`
|
||||||
|
} else {
|
||||||
|
from = `>=${from}${incPr ? '-0' : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isX(tM)) {
|
||||||
|
to = ''
|
||||||
|
} else if (isX(tm)) {
|
||||||
|
to = `<${+tM + 1}.0.0-0`
|
||||||
|
} else if (isX(tp)) {
|
||||||
|
to = `<${tM}.${+tm + 1}.0-0`
|
||||||
|
} else if (tpr) {
|
||||||
|
to = `<=${tM}.${tm}.${tp}-${tpr}`
|
||||||
|
} else if (incPr) {
|
||||||
|
to = `<${tM}.${tm}.${+tp + 1}-0`
|
||||||
|
} else {
|
||||||
|
to = `<=${to}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${from} ${to}`.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
const testSet = (set, version, options) => {
|
||||||
|
for (let i = 0; i < set.length; i++) {
|
||||||
|
if (!set[i].test(version)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version.prerelease.length && !options.includePrerelease) {
|
||||||
|
// Find the set of versions that are allowed to have prereleases
|
||||||
|
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
|
||||||
|
// That should allow `1.2.3-pr.2` to pass.
|
||||||
|
// However, `1.2.4-alpha.notready` should NOT be allowed,
|
||||||
|
// even though it's within the range set by the comparators.
|
||||||
|
for (let i = 0; i < set.length; i++) {
|
||||||
|
debug(set[i].semver)
|
||||||
|
if (set[i].semver === Comparator.ANY) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (set[i].semver.prerelease.length > 0) {
|
||||||
|
const allowed = set[i].semver
|
||||||
|
if (allowed.major === version.major &&
|
||||||
|
allowed.minor === version.minor &&
|
||||||
|
allowed.patch === version.patch) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Version has a -pre, but it's not one of the ones we like.
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
@ -0,0 +1,302 @@
|
|||||||
|
const debug = require('../internal/debug')
|
||||||
|
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
|
||||||
|
const { safeRe: re, t } = require('../internal/re')
|
||||||
|
|
||||||
|
const parseOptions = require('../internal/parse-options')
|
||||||
|
const { compareIdentifiers } = require('../internal/identifiers')
|
||||||
|
class SemVer {
|
||||||
|
constructor (version, options) {
|
||||||
|
options = parseOptions(options)
|
||||||
|
|
||||||
|
if (version instanceof SemVer) {
|
||||||
|
if (version.loose === !!options.loose &&
|
||||||
|
version.includePrerelease === !!options.includePrerelease) {
|
||||||
|
return version
|
||||||
|
} else {
|
||||||
|
version = version.version
|
||||||
|
}
|
||||||
|
} else if (typeof version !== 'string') {
|
||||||
|
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version.length > MAX_LENGTH) {
|
||||||
|
throw new TypeError(
|
||||||
|
`version is longer than ${MAX_LENGTH} characters`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
debug('SemVer', version, options)
|
||||||
|
this.options = options
|
||||||
|
this.loose = !!options.loose
|
||||||
|
// this isn't actually relevant for versions, but keep it so that we
|
||||||
|
// don't run into trouble passing this.options around.
|
||||||
|
this.includePrerelease = !!options.includePrerelease
|
||||||
|
|
||||||
|
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
|
||||||
|
|
||||||
|
if (!m) {
|
||||||
|
throw new TypeError(`Invalid Version: ${version}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.raw = version
|
||||||
|
|
||||||
|
// these are actually numbers
|
||||||
|
this.major = +m[1]
|
||||||
|
this.minor = +m[2]
|
||||||
|
this.patch = +m[3]
|
||||||
|
|
||||||
|
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
|
||||||
|
throw new TypeError('Invalid major version')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
|
||||||
|
throw new TypeError('Invalid minor version')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
|
||||||
|
throw new TypeError('Invalid patch version')
|
||||||
|
}
|
||||||
|
|
||||||
|
// numberify any prerelease numeric ids
|
||||||
|
if (!m[4]) {
|
||||||
|
this.prerelease = []
|
||||||
|
} else {
|
||||||
|
this.prerelease = m[4].split('.').map((id) => {
|
||||||
|
if (/^[0-9]+$/.test(id)) {
|
||||||
|
const num = +id
|
||||||
|
if (num >= 0 && num < MAX_SAFE_INTEGER) {
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
this.build = m[5] ? m[5].split('.') : []
|
||||||
|
this.format()
|
||||||
|
}
|
||||||
|
|
||||||
|
format () {
|
||||||
|
this.version = `${this.major}.${this.minor}.${this.patch}`
|
||||||
|
if (this.prerelease.length) {
|
||||||
|
this.version += `-${this.prerelease.join('.')}`
|
||||||
|
}
|
||||||
|
return this.version
|
||||||
|
}
|
||||||
|
|
||||||
|
toString () {
|
||||||
|
return this.version
|
||||||
|
}
|
||||||
|
|
||||||
|
compare (other) {
|
||||||
|
debug('SemVer.compare', this.version, this.options, other)
|
||||||
|
if (!(other instanceof SemVer)) {
|
||||||
|
if (typeof other === 'string' && other === this.version) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
other = new SemVer(other, this.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (other.version === this.version) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.compareMain(other) || this.comparePre(other)
|
||||||
|
}
|
||||||
|
|
||||||
|
compareMain (other) {
|
||||||
|
if (!(other instanceof SemVer)) {
|
||||||
|
other = new SemVer(other, this.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
compareIdentifiers(this.major, other.major) ||
|
||||||
|
compareIdentifiers(this.minor, other.minor) ||
|
||||||
|
compareIdentifiers(this.patch, other.patch)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
comparePre (other) {
|
||||||
|
if (!(other instanceof SemVer)) {
|
||||||
|
other = new SemVer(other, this.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOT having a prerelease is > having one
|
||||||
|
if (this.prerelease.length && !other.prerelease.length) {
|
||||||
|
return -1
|
||||||
|
} else if (!this.prerelease.length && other.prerelease.length) {
|
||||||
|
return 1
|
||||||
|
} else if (!this.prerelease.length && !other.prerelease.length) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
let i = 0
|
||||||
|
do {
|
||||||
|
const a = this.prerelease[i]
|
||||||
|
const b = other.prerelease[i]
|
||||||
|
debug('prerelease compare', i, a, b)
|
||||||
|
if (a === undefined && b === undefined) {
|
||||||
|
return 0
|
||||||
|
} else if (b === undefined) {
|
||||||
|
return 1
|
||||||
|
} else if (a === undefined) {
|
||||||
|
return -1
|
||||||
|
} else if (a === b) {
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
return compareIdentifiers(a, b)
|
||||||
|
}
|
||||||
|
} while (++i)
|
||||||
|
}
|
||||||
|
|
||||||
|
compareBuild (other) {
|
||||||
|
if (!(other instanceof SemVer)) {
|
||||||
|
other = new SemVer(other, this.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
let i = 0
|
||||||
|
do {
|
||||||
|
const a = this.build[i]
|
||||||
|
const b = other.build[i]
|
||||||
|
debug('prerelease compare', i, a, b)
|
||||||
|
if (a === undefined && b === undefined) {
|
||||||
|
return 0
|
||||||
|
} else if (b === undefined) {
|
||||||
|
return 1
|
||||||
|
} else if (a === undefined) {
|
||||||
|
return -1
|
||||||
|
} else if (a === b) {
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
return compareIdentifiers(a, b)
|
||||||
|
}
|
||||||
|
} while (++i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// preminor will bump the version up to the next minor release, and immediately
|
||||||
|
// down to pre-release. premajor and prepatch work the same way.
|
||||||
|
inc (release, identifier, identifierBase) {
|
||||||
|
switch (release) {
|
||||||
|
case 'premajor':
|
||||||
|
this.prerelease.length = 0
|
||||||
|
this.patch = 0
|
||||||
|
this.minor = 0
|
||||||
|
this.major++
|
||||||
|
this.inc('pre', identifier, identifierBase)
|
||||||
|
break
|
||||||
|
case 'preminor':
|
||||||
|
this.prerelease.length = 0
|
||||||
|
this.patch = 0
|
||||||
|
this.minor++
|
||||||
|
this.inc('pre', identifier, identifierBase)
|
||||||
|
break
|
||||||
|
case 'prepatch':
|
||||||
|
// If this is already a prerelease, it will bump to the next version
|
||||||
|
// drop any prereleases that might already exist, since they are not
|
||||||
|
// relevant at this point.
|
||||||
|
this.prerelease.length = 0
|
||||||
|
this.inc('patch', identifier, identifierBase)
|
||||||
|
this.inc('pre', identifier, identifierBase)
|
||||||
|
break
|
||||||
|
// If the input is a non-prerelease version, this acts the same as
|
||||||
|
// prepatch.
|
||||||
|
case 'prerelease':
|
||||||
|
if (this.prerelease.length === 0) {
|
||||||
|
this.inc('patch', identifier, identifierBase)
|
||||||
|
}
|
||||||
|
this.inc('pre', identifier, identifierBase)
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'major':
|
||||||
|
// If this is a pre-major version, bump up to the same major version.
|
||||||
|
// Otherwise increment major.
|
||||||
|
// 1.0.0-5 bumps to 1.0.0
|
||||||
|
// 1.1.0 bumps to 2.0.0
|
||||||
|
if (
|
||||||
|
this.minor !== 0 ||
|
||||||
|
this.patch !== 0 ||
|
||||||
|
this.prerelease.length === 0
|
||||||
|
) {
|
||||||
|
this.major++
|
||||||
|
}
|
||||||
|
this.minor = 0
|
||||||
|
this.patch = 0
|
||||||
|
this.prerelease = []
|
||||||
|
break
|
||||||
|
case 'minor':
|
||||||
|
// If this is a pre-minor version, bump up to the same minor version.
|
||||||
|
// Otherwise increment minor.
|
||||||
|
// 1.2.0-5 bumps to 1.2.0
|
||||||
|
// 1.2.1 bumps to 1.3.0
|
||||||
|
if (this.patch !== 0 || this.prerelease.length === 0) {
|
||||||
|
this.minor++
|
||||||
|
}
|
||||||
|
this.patch = 0
|
||||||
|
this.prerelease = []
|
||||||
|
break
|
||||||
|
case 'patch':
|
||||||
|
// If this is not a pre-release version, it will increment the patch.
|
||||||
|
// If it is a pre-release it will bump up to the same patch version.
|
||||||
|
// 1.2.0-5 patches to 1.2.0
|
||||||
|
// 1.2.0 patches to 1.2.1
|
||||||
|
if (this.prerelease.length === 0) {
|
||||||
|
this.patch++
|
||||||
|
}
|
||||||
|
this.prerelease = []
|
||||||
|
break
|
||||||
|
// This probably shouldn't be used publicly.
|
||||||
|
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
|
||||||
|
case 'pre': {
|
||||||
|
const base = Number(identifierBase) ? 1 : 0
|
||||||
|
|
||||||
|
if (!identifier && identifierBase === false) {
|
||||||
|
throw new Error('invalid increment argument: identifier is empty')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.prerelease.length === 0) {
|
||||||
|
this.prerelease = [base]
|
||||||
|
} else {
|
||||||
|
let i = this.prerelease.length
|
||||||
|
while (--i >= 0) {
|
||||||
|
if (typeof this.prerelease[i] === 'number') {
|
||||||
|
this.prerelease[i]++
|
||||||
|
i = -2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (i === -1) {
|
||||||
|
// didn't increment anything
|
||||||
|
if (identifier === this.prerelease.join('.') && identifierBase === false) {
|
||||||
|
throw new Error('invalid increment argument: identifier already exists')
|
||||||
|
}
|
||||||
|
this.prerelease.push(base)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (identifier) {
|
||||||
|
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
|
||||||
|
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
|
||||||
|
let prerelease = [identifier, base]
|
||||||
|
if (identifierBase === false) {
|
||||||
|
prerelease = [identifier]
|
||||||
|
}
|
||||||
|
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
|
||||||
|
if (isNaN(this.prerelease[1])) {
|
||||||
|
this.prerelease = prerelease
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.prerelease = prerelease
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error(`invalid increment argument: ${release}`)
|
||||||
|
}
|
||||||
|
this.raw = this.format()
|
||||||
|
if (this.build.length) {
|
||||||
|
this.raw += `+${this.build.join('.')}`
|
||||||
|
}
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = SemVer
|
@ -0,0 +1,6 @@
|
|||||||
|
const parse = require('./parse')
|
||||||
|
const clean = (version, options) => {
|
||||||
|
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
|
||||||
|
return s ? s.version : null
|
||||||
|
}
|
||||||
|
module.exports = clean
|
@ -0,0 +1,52 @@
|
|||||||
|
const eq = require('./eq')
|
||||||
|
const neq = require('./neq')
|
||||||
|
const gt = require('./gt')
|
||||||
|
const gte = require('./gte')
|
||||||
|
const lt = require('./lt')
|
||||||
|
const lte = require('./lte')
|
||||||
|
|
||||||
|
const cmp = (a, op, b, loose) => {
|
||||||
|
switch (op) {
|
||||||
|
case '===':
|
||||||
|
if (typeof a === 'object') {
|
||||||
|
a = a.version
|
||||||
|
}
|
||||||
|
if (typeof b === 'object') {
|
||||||
|
b = b.version
|
||||||
|
}
|
||||||
|
return a === b
|
||||||
|
|
||||||
|
case '!==':
|
||||||
|
if (typeof a === 'object') {
|
||||||
|
a = a.version
|
||||||
|
}
|
||||||
|
if (typeof b === 'object') {
|
||||||
|
b = b.version
|
||||||
|
}
|
||||||
|
return a !== b
|
||||||
|
|
||||||
|
case '':
|
||||||
|
case '=':
|
||||||
|
case '==':
|
||||||
|
return eq(a, b, loose)
|
||||||
|
|
||||||
|
case '!=':
|
||||||
|
return neq(a, b, loose)
|
||||||
|
|
||||||
|
case '>':
|
||||||
|
return gt(a, b, loose)
|
||||||
|
|
||||||
|
case '>=':
|
||||||
|
return gte(a, b, loose)
|
||||||
|
|
||||||
|
case '<':
|
||||||
|
return lt(a, b, loose)
|
||||||
|
|
||||||
|
case '<=':
|
||||||
|
return lte(a, b, loose)
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new TypeError(`Invalid operator: ${op}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = cmp
|
@ -0,0 +1,52 @@
|
|||||||
|
const SemVer = require('../classes/semver')
|
||||||
|
const parse = require('./parse')
|
||||||
|
const { safeRe: re, t } = require('../internal/re')
|
||||||
|
|
||||||
|
const coerce = (version, options) => {
|
||||||
|
if (version instanceof SemVer) {
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof version === 'number') {
|
||||||
|
version = String(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof version !== 'string') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
options = options || {}
|
||||||
|
|
||||||
|
let match = null
|
||||||
|
if (!options.rtl) {
|
||||||
|
match = version.match(re[t.COERCE])
|
||||||
|
} else {
|
||||||
|
// Find the right-most coercible string that does not share
|
||||||
|
// a terminus with a more left-ward coercible string.
|
||||||
|
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
|
||||||
|
//
|
||||||
|
// Walk through the string checking with a /g regexp
|
||||||
|
// Manually set the index so as to pick up overlapping matches.
|
||||||
|
// Stop when we get a match that ends at the string end, since no
|
||||||
|
// coercible string can be more right-ward without the same terminus.
|
||||||
|
let next
|
||||||
|
while ((next = re[t.COERCERTL].exec(version)) &&
|
||||||
|
(!match || match.index + match[0].length !== version.length)
|
||||||
|
) {
|
||||||
|
if (!match ||
|
||||||
|
next.index + next[0].length !== match.index + match[0].length) {
|
||||||
|
match = next
|
||||||
|
}
|
||||||
|
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
|
||||||
|
}
|
||||||
|
// leave it in a clean state
|
||||||
|
re[t.COERCERTL].lastIndex = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (match === null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
|
||||||
|
}
|
||||||
|
module.exports = coerce
|
@ -0,0 +1,7 @@
|
|||||||
|
const SemVer = require('../classes/semver')
|
||||||
|
const compareBuild = (a, b, loose) => {
|
||||||
|
const versionA = new SemVer(a, loose)
|
||||||
|
const versionB = new SemVer(b, loose)
|
||||||
|
return versionA.compare(versionB) || versionA.compareBuild(versionB)
|
||||||
|
}
|
||||||
|
module.exports = compareBuild
|
@ -0,0 +1,3 @@
|
|||||||
|
const compare = require('./compare')
|
||||||
|
const compareLoose = (a, b) => compare(a, b, true)
|
||||||
|
module.exports = compareLoose
|
@ -0,0 +1,5 @@
|
|||||||
|
const SemVer = require('../classes/semver')
|
||||||
|
const compare = (a, b, loose) =>
|
||||||
|
new SemVer(a, loose).compare(new SemVer(b, loose))
|
||||||
|
|
||||||
|
module.exports = compare
|
@ -0,0 +1,65 @@
|
|||||||
|
const parse = require('./parse.js')
|
||||||
|
|
||||||
|
const diff = (version1, version2) => {
|
||||||
|
const v1 = parse(version1, null, true)
|
||||||
|
const v2 = parse(version2, null, true)
|
||||||
|
const comparison = v1.compare(v2)
|
||||||
|
|
||||||
|
if (comparison === 0) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const v1Higher = comparison > 0
|
||||||
|
const highVersion = v1Higher ? v1 : v2
|
||||||
|
const lowVersion = v1Higher ? v2 : v1
|
||||||
|
const highHasPre = !!highVersion.prerelease.length
|
||||||
|
const lowHasPre = !!lowVersion.prerelease.length
|
||||||
|
|
||||||
|
if (lowHasPre && !highHasPre) {
|
||||||
|
// Going from prerelease -> no prerelease requires some special casing
|
||||||
|
|
||||||
|
// If the low version has only a major, then it will always be a major
|
||||||
|
// Some examples:
|
||||||
|
// 1.0.0-1 -> 1.0.0
|
||||||
|
// 1.0.0-1 -> 1.1.1
|
||||||
|
// 1.0.0-1 -> 2.0.0
|
||||||
|
if (!lowVersion.patch && !lowVersion.minor) {
|
||||||
|
return 'major'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise it can be determined by checking the high version
|
||||||
|
|
||||||
|
if (highVersion.patch) {
|
||||||
|
// anything higher than a patch bump would result in the wrong version
|
||||||
|
return 'patch'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (highVersion.minor) {
|
||||||
|
// anything higher than a minor bump would result in the wrong version
|
||||||
|
return 'minor'
|
||||||
|
}
|
||||||
|
|
||||||
|
// bumping major/minor/patch all have same result
|
||||||
|
return 'major'
|
||||||
|
}
|
||||||
|
|
||||||
|
// add the `pre` prefix if we are going to a prerelease version
|
||||||
|
const prefix = highHasPre ? 'pre' : ''
|
||||||
|
|
||||||
|
if (v1.major !== v2.major) {
|
||||||
|
return prefix + 'major'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v1.minor !== v2.minor) {
|
||||||
|
return prefix + 'minor'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v1.patch !== v2.patch) {
|
||||||
|
return prefix + 'patch'
|
||||||
|
}
|
||||||
|
|
||||||
|
// high and low are preleases
|
||||||
|
return 'prerelease'
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = diff
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue