Skip to content

migrate commonjs to esm #574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
additional_dependencies:
- setuptools

# Autoformat: markdown, javacsript
# Autoformat: markdown, javascript
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
hooks:
Expand Down
19 changes: 10 additions & 9 deletions bin/configurable-http-proxy
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
//
"use strict";

const fs = require("fs"),
pkg = require("../package.json"),
{ Command } = require("commander"),
tls = require("tls"),
winston = require("winston");
import fs from "node:fs";
import { Command } from "commander";

import ConfigurableProxy from "../lib/configproxy.js";
import { defaultLogger } from "../lib/log.js";

import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const pkg = require("../package.json");

const cli = new Command();
cli
Expand Down Expand Up @@ -130,9 +133,7 @@ function collectHeadersIntoObject(value, previous) {
cli.parse(process.argv);
var args = cli.opts();

var ConfigurableProxy = require("../lib/configproxy.js").ConfigurableProxy;

var log = require("../lib/log.js").defaultLogger({ level: args.logLevel.toLowerCase() });
var log = defaultLogger({ level: args.logLevel.toLowerCase() });
var options = { log: log };

var sslCiphers;
Expand Down
11 changes: 5 additions & 6 deletions eslint.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,22 @@ const js = require("@eslint/js");
module.exports = defineConfig([
js.configs.recommended,
{
files: ["bin/*", "**/*.js"],
files: ["bin/configurable-http-proxy", "**/*js"],
languageOptions: {
sourceType: "commonjs",
ecmaVersion: 2022,
globals: {
...globals.node,
...globals.nodeBuiltin,
},
},
rules: {
"no-unused-vars": ["error", { args: "none" }],
},
},
{
files: ["test/**/*.js"],
files: ["test/**/*js"],
languageOptions: {
sourceType: "commonjs",
globals: {
...globals.node,
...globals.nodeBuiltin,
...globals.jasmine,
},
},
Expand Down
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
module.exports = require("./lib/configproxy.js");
export * from "./lib/configproxy.js";
export { default } from "./lib/configproxy.js";
32 changes: 19 additions & 13 deletions lib/configproxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,23 @@
// POST, DELETE to /api/routes[:/path/to/proxy] to update the routing table
// GET /api/routes to see the current routing table
//
"use strict";

var http = require("http"),
https = require("https"),
fs = require("fs"),
path = require("path"),
EventEmitter = require("events").EventEmitter,
httpProxy = require("http-proxy-3"),
defaultLogger = require("./log").defaultLogger,
metrics = require("./metrics");
import fs from "node:fs";
import http from "node:http";
import https from "node:https";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { EventEmitter } from "node:events";
import { default as httpProxy } from "http-proxy-3";

import { defaultLogger } from "./log.js";
import * as metrics from "./metrics.js";
import { MemoryStore } from "./store.js";

const require = createRequire(import.meta.url);

const __dirname = path.dirname(fileURLToPath(import.meta.url));

function bound(that, method) {
// bind a method, to ensure `this=that` when it is called
Expand Down Expand Up @@ -123,16 +130,15 @@ const loadStorage = (options) => {
}

// loads default storage strategy
const store = require("./store.js");
return new store.MemoryStore(options);
return new MemoryStore(options);
};

function _logUrl(url) {
// format a url for logging, e.g. strip url params
if (url) return url.split("?", 1)[0];
}

class ConfigurableProxy extends EventEmitter {
export class ConfigurableProxy extends EventEmitter {
constructor(options) {
super();
var that = this;
Expand Down Expand Up @@ -671,4 +677,4 @@ class ConfigurableProxy extends EventEmitter {
}
}

exports.ConfigurableProxy = ConfigurableProxy;
export default ConfigurableProxy;
7 changes: 2 additions & 5 deletions lib/log.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"use strict";
const winston = require("winston");
import winston from "winston";

const simpleFormat = winston.format.printf((info) => {
// console.log(info);
return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`;
});

function defaultLogger(options) {
export function defaultLogger(options) {
options = options || {};
options.format = winston.format.combine(
winston.format.colorize(),
Expand All @@ -18,5 +17,3 @@ function defaultLogger(options) {
options.transports = [new winston.transports.Console()];
return winston.createLogger(options);
}

exports.defaultLogger = defaultLogger;
13 changes: 3 additions & 10 deletions lib/metrics.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"use strict";
import * as client from "prom-client";

var client = require("prom-client");

class Metrics {
export class Metrics {
constructor() {
this.register = new client.Registry();
client.collectDefaultMetrics({ register: this.register });
Expand Down Expand Up @@ -73,7 +71,7 @@ class Metrics {
}
}

class MockMetrics {
export class MockMetrics {
constructor() {
return new Proxy(this, {
get(target, name) {
Expand Down Expand Up @@ -106,8 +104,3 @@ class MockMetrics {
return Promise.resolve();
}
}

module.exports = {
Metrics,
MockMetrics,
};
8 changes: 3 additions & 5 deletions lib/store.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use strict";

var trie = require("./trie.js");
import * as trie from "./trie.js";

var NotImplemented = function (name) {
return {
Expand All @@ -9,7 +9,7 @@ var NotImplemented = function (name) {
};
};

class BaseStore {
export class BaseStore {
// "abstract" methods
getTarget(path) {
throw NotImplemented("getTarget");
Expand Down Expand Up @@ -39,7 +39,7 @@ class BaseStore {
}
}

class MemoryStore extends BaseStore {
export class MemoryStore extends BaseStore {
constructor() {
super();
this.routes = {};
Expand Down Expand Up @@ -77,5 +77,3 @@ class MemoryStore extends BaseStore {
return Promise.resolve(route);
}
}

exports.MemoryStore = MemoryStore;
36 changes: 17 additions & 19 deletions lib/testutil.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
"use strict";

var http = require("http");
var extend = require("util")._extend;
var WebSocketServer = require("ws").WebSocketServer;

var configproxy = require("./configproxy");
var defaultLogger = require("./log").defaultLogger;
import http from "node:http";
import { WebSocketServer } from "ws";
import { ConfigurableProxy } from "./configproxy.js";
import { defaultLogger } from "./log.js";

var servers = [];

function addTarget(proxy, path, port, websocket, targetPath) {
export function addTarget(proxy, path, port, websocket, targetPath) {
var target = "http://127.0.0.1:" + port;
if (targetPath) {
target = target + targetPath;
Expand All @@ -21,7 +19,8 @@ function addTarget(proxy, path, port, websocket, targetPath) {
};

server = http.createServer(function (req, res) {
var reply = extend({}, data);
var reply = {};
Object.assign(reply, data);
reply.url = req.url;
reply.headers = req.headers;
res.write(JSON.stringify(reply));
Expand All @@ -33,7 +32,8 @@ function addTarget(proxy, path, port, websocket, targetPath) {
});
wss.on("connection", function (ws) {
ws.on("message", function (message) {
var reply = extend({}, data);
var reply = {};
Object.assign(reply, data);
reply.message = message.toString();
ws.send(JSON.stringify(reply));
});
Expand All @@ -50,9 +50,7 @@ function addTarget(proxy, path, port, websocket, targetPath) {
});
}

exports.addTarget = addTarget;

exports.addTargetRedirecting = function (proxy, path, port, targetPath, redirectTo) {
export function addTargetRedirecting(proxy, path, port, targetPath, redirectTo) {
// Like the above, but the server returns a redirect response with a Location header.
// Cannot use default arguments as they are apparently not supported.
var target = "http://127.0.0.1:" + port;
Expand All @@ -71,9 +69,9 @@ exports.addTargetRedirecting = function (proxy, path, port, targetPath, redirect
server.listen(port);
servers.push(server);
});
};
}

function addTargets(proxy, paths, port) {
export function addTargets(proxy, paths, port) {
if (paths.length === 0) {
return Promise.resolve();
}
Expand All @@ -82,12 +80,12 @@ function addTargets(proxy, paths, port) {
});
}

exports.setupProxy = function (port, options, paths) {
export function setupProxy(port, options, paths) {
options = options || {};
options.authToken = "secret";
options.log = defaultLogger({ level: "error" });

var proxy = new configproxy.ConfigurableProxy(options);
var proxy = new ConfigurableProxy(options);
proxy._setup_timestamp = new Date(new Date().getTime() - 60000);
var ip = "127.0.0.1";
var countdown = 2;
Expand Down Expand Up @@ -136,9 +134,9 @@ exports.setupProxy = function (port, options, paths) {
}
});
return p;
};
}

exports.teardownServers = function (callback) {
export function teardownServers(callback) {
var count = 0;
var onclose = function () {
count = count + 1;
Expand All @@ -153,4 +151,4 @@ exports.teardownServers = function (callback) {
// but this avoids waits between all tests with node 18
servers[i].closeAllConnections();
}
};
}
14 changes: 4 additions & 10 deletions lib/trie.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
//
// Get data for a prefix with Trie.get("/path/to/something/inside")
//
"use strict";

function trimPrefix(prefix) {
export function trimPrefix(prefix) {
// cleanup prefix form: /foo/bar
// ensure prefix starts with /
if (prefix.length === 0 || prefix[0] !== "/") {
Expand All @@ -22,17 +21,16 @@ function trimPrefix(prefix) {
return prefix;
}

exports.trimPrefix = trimPrefix;

function URLTrie(prefix) {
export function URLTrie(prefix) {
// create a new URLTrie with data
this.prefix = trimPrefix(prefix || "/");
this.branches = {};
this.size = 0;
}

var _slashesRe = /^[/]+|[/]+$/g;
function stringToPath(s) {

export function stringToPath(s) {
// turn a /prefix/string/ into ['prefix', 'string']
s = s.replace(_slashesRe, "");
if (s.length === 0) {
Expand All @@ -43,8 +41,6 @@ function stringToPath(s) {
}
}

exports.stringToPath = stringToPath;

URLTrie.prototype.add = function (path, data) {
// add data to a node in the trie at path
if (typeof path === "string") {
Expand Down Expand Up @@ -125,5 +121,3 @@ URLTrie.prototype.get = function (path) {
}
}
};

exports.URLTrie = URLTrie;
Loading