Full Code of nodyn/jvm-npm for AI

master 106336e2d073 cached
41 files
30.1 KB
9.2k tokens
20 symbols
1 requests
Download .txt
Repository: nodyn/jvm-npm
Branch: master
Commit: 106336e2d073
Files: 41
Total size: 30.1 KB

Directory structure:
gitextract_3ejd1flu/

├── .eslintrc.json
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── examples/
│   ├── simple/
│   │   ├── app.js
│   │   └── my-module.js
│   └── underscore/
│       ├── README.md
│       ├── app.js
│       └── package.json
├── package.json
├── pom.xml
└── src/
    ├── main/
    │   └── javascript/
    │       └── jvm-npm.js
    └── test/
        ├── javascript/
        │   └── specs/
        │       ├── lib/
        │       │   ├── a_package/
        │       │   │   ├── index.js
        │       │   │   └── lib/
        │       │   │       └── parent.js
        │       │   ├── cheese/
        │       │   │   ├── lib/
        │       │   │   │   └── index.js
        │       │   │   └── package.json
        │       │   ├── cyclic/
        │       │   │   ├── a.js
        │       │   │   ├── b.js
        │       │   │   └── index.js
        │       │   ├── cyclic2/
        │       │   │   ├── stream.js
        │       │   │   └── stream_readable.js
        │       │   ├── isolation/
        │       │   │   ├── module-a.js
        │       │   │   ├── module-b.js
        │       │   │   ├── module-c.js
        │       │   │   └── module-d.js
        │       │   ├── mod_exports.js
        │       │   ├── my_package/
        │       │   │   └── index.js
        │       │   ├── native_test_module.js
        │       │   ├── other_package/
        │       │   │   ├── lib/
        │       │   │   │   ├── foo.js
        │       │   │   │   └── subdir/
        │       │   │   │       └── bar.js
        │       │   │   └── package.json
        │       │   ├── outer.js
        │       │   ├── simple_module.js
        │       │   ├── some_data.json
        │       │   ├── sub/
        │       │   │   └── inner.js
        │       │   └── throws.js
        │       └── requireSpec.js
        └── resources/
            ├── _core.js
            └── core.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .eslintrc.json
================================================
{
  "extends": "semistandard",
  "globals": {
    "java": false,
    "NativeRequire": true
  },
  "rules": {
    "no-global-assign": [
      "error",
      {
        "exceptions": [
          "module",
          "require"
        ]
      }
    ],
    "no-native-reassign": [
      "error",
      {
        "exceptions": [
          "module",
          "require"
        ]
      }
    ],
    "no-extend-native": [
      "error",
      {
        "exceptions": [
          "String"
        ]
      }
    ],
    "no-new-func": "off"
  }
}

================================================
FILE: .gitignore
================================================
target
node_modules
.idea
*.iml
*.log


================================================
FILE: .travis.yml
================================================
sudo: required
dist: trusty
language: java
jdk:
  - openjdk8
before_script:
script:
   - make ci
branches:
  only:
    - master
notifications:
  irc: "irc.freenode.org#brass-monkey"

================================================
FILE: LICENSE
================================================
Copyright 2014-2016 Red Hat, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: Makefile
================================================
ci: test

test: lint
	npm run test

lint: node_modules
	npm run lint

clean:
	rm -rf node_modules target

node_modules: package.json
	npm install

.PHONY: node_modules

================================================
FILE: README.md
================================================
# jvm-npm

Support for NPM module loading in Javascript runtimes on the JVM.
Implementation is based on http://nodejs.org/api/modules.html and
should be fully compatible. This, of course, does not include the
full node.js API, so don't expect all of the standard NPM modules
that depend on it to work. If you want to use existing NPM modules
that depend on the Node.js API, consider the not-yet-fully-baked
[nodyn project](http://nodyn.io). If you are writing your own NPM
modules in DynJS, Rhino or Nashorn, this should work just fine.

This module is known to work with DynJS, and has been briefly tested
on Nashorn, and should work with Rhino as well. 

## Usage

Using the global `load()` functions supplied by DynJS, Nashorn and
Rhino, load `jvm-npm.js` into the global execution context:

    dynjs> load('./jvm-npm.js');
    dynjs> var x = require('some_module');

Or with Nashorn:

    nashorn> load('./jvm-npm.js');
    nashorn> var x = require('some_module');
    
Of course, you will need to ensure that the jvm-npm.js file exists
in the current directory.

See the `examples` directory for simple, runnable usage examples.
Again, this will only work out of the box for pure JS NPM modules.
Anything that depends on the Node.js API will not work with just
this file.


================================================
FILE: examples/simple/app.js
================================================
load('../../src/main/javascript/jvm-npm.js');
var hello = require('./my-module');
hello('Bob!');


================================================
FILE: examples/simple/my-module.js
================================================
module.exports = function sayHello(name) {
  java.lang.System.out.println("Hello " + name);
};



================================================
FILE: examples/underscore/README.md
================================================
# Example: underscore.js

To run the example, you should have either dynjs or jrunscript
(Nashorn) in your PATH. And you need to install the underscore NPM
module. First do that.

    $ npm install

This will look at `package.json`, determine the app dependencies and
download them for you in `./node_modules`. Next choose your runtime,
and run the app.

    $ dynjs app.js

Or 

    $ nashorn app.js

Either should work.


================================================
FILE: examples/underscore/app.js
================================================
load('../../src/main/javascript/jvm-npm.js');
var _ = require('underscore');

print('Here we do some stuff with underscore');

example("_.each", function() {
  _.each([1, 2, 3], print);
});

example("_.map", function() {
  print(_.map([1, 2, 3], function(num){ return num * 3; }));
});

example("_.reduce", function() {
  print(_.reduce([1, 2, 3], function(memo, num){ 
    return memo + num; 
  }, 0));
});

example("_.reduceRight", function() {
  var list = [[0, 1], [2, 3], [4, 5]];
  var flat = _.reduceRight(list, function(a, b) { 
    return a.concat(b); 
  }, []);
  print(flat);
});

example("_.find", function() {
  var even = _.find([1, 2, 3, 4, 5, 6], function(num){ 
    return num % 2 === 0; 
  });
  print(even);
});

example("_.filter", function() {
  var even = _.filter([1, 2, 3, 4, 5, 6], function(num){ 
    return num % 2 === 0; 
  });
  print(even);
});

function example(name, ex) {
  print(["", name].join("\n"));
  print(ex);
  ex();
}


================================================
FILE: examples/underscore/package.json
================================================
{
  "name": "jvm-npm-underscore",
  "description": "example application using underscore.js on the JVM",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "underscore": "1.6.0"
  }
}


================================================
FILE: package.json
================================================
{
  "name": "jvm-npm",
  "version": "0.1.1",
  "description": "Support for NPM module loading in Javascript runtimes on the JVM",
  "main": "src/main/javascript/jvm-npm.js",
  "directories": {
    "example": "examples"
  },
  "scripts": {
    "test": "mvn integration-test",
    "lint": "eslint src/main/javascript/jvm-npm.js"
  },
  "files": [
    "package.json",
    "pom.xml",
    "README.md",
    "src"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/nodyn/jvm-npm.git"
  },
  "author": "Lance Ball <lball@redhat.com> (http://lanceball.com)",
  "contributors": [
    "Bob McWhirter <bmcwhirter@redhat.com>",
    "Helio Frota <hesilva@redhat.com> (http://lanceball.com)"],
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/nodyn/jvm-npm/issues"
  },
  "homepage": "https://github.com/nodyn/jvm-npm#readme",
  "devDependencies": {
    "eslint": "^3.5.0",
    "eslint-config-semistandard": "^7.0.0",
    "eslint-config-standard": "^6.0.1",
    "eslint-plugin-promise": "^2.0.1",
    "eslint-plugin-react": "^6.2.2",
    "eslint-plugin-standard": "^2.0.0"
  }
}


================================================
FILE: pom.xml
================================================
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


  <modelVersion>4.0.0</modelVersion>

  <groupId>io.nodyn</groupId>
  <artifactId>jvm-npm</artifactId>
  <version>0.1.0-SNAPSHOT</version>
  <url>http://github.com/nodyn/jvm-npm</url>
  <name>jvm-npm</name>

  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>7</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <version.dynjs>0.2.3-SNAPSHOT</version.dynjs>
    <version.jasmine-cli>0.0.12</version.jasmine-cli>
  </properties>

  <developers>
    <developer>
      <id>lanceball</id>
      <name>Lance Ball</name>
      <url>http://lanceball.com</url>
      <email>lball@redhat.com</email>
    </developer>
  </developers>

  <scm>
    <connection>scm:git:git@github.com:nodyn/jvm-npm.git</connection>
    <developerConnection>scm:git:git@github.com:nodyn/jvm-npm.git</developerConnection>
    <url>git@github.com:nodyn/jvm-npm.git</url>
    <tag>HEAD</tag>
  </scm>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <dependencies>
    <dependency>
      <groupId>org.dynjs</groupId>
      <artifactId>dynjs</artifactId>
      <version>${version.dynjs}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.akiellor.jasmine</groupId>
      <artifactId>jasmine-cli</artifactId>
      <version>${version.jasmine-cli}</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.dynjs</groupId>
          <artifactId>dynjs</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.projectodd.rephract</groupId>
          <artifactId>rephract</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

  <build>
    <extensions>
      <extension>
        <groupId>org.apache.maven.wagon</groupId>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <version>1.0-beta-7</version>
      </extension>
    </extensions>
    <resources>
      <resource>
        <directory>src/main/javascript</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>attach-artifact</goal>
            </goals>
            <phase>package</phase>
            <configuration>
              <artifacts>
                <artifact>
                  <file>target/classes/jvm-npm.js</file>
                  <type>js</type>
                </artifact>
              </artifacts>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <encoding>${project.build.sourceEncoding}</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution>
            <id>enforce-maven</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireMavenVersion>
                  <version>3.0.0</version>
                </requireMavenVersion>
              </rules>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <id>Jasmine Integration Tests</id>
            <phase>integration-test</phase>
            <goals>
              <goal>java</goal>
            </goals>
            <configuration>
              <mainClass>org.jasmine.cli.Main</mainClass>
              <classpathScope>test</classpathScope>
              <systemPropertyVariables>
                <dynjs.compile.mode>OFF</dynjs.compile.mode>
              </systemPropertyVariables>
              <arguments>
                <argument>--pattern</argument>
                <argument>./src/test/javascript/**/*Spec.js</argument>
                <argument>--format</argument>
                <argument>DOC</argument>
                <argument>--compile-mode</argument>
                <argument>OFF</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


================================================
FILE: src/main/javascript/jvm-npm.js
================================================
/**
 *  Copyright 2014-2016 Red Hat, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License")
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
// Since we intend to use the Function constructor.
/* jshint evil: true */

module = (typeof module === 'undefined') ? {} : module;

(function () {
  var System = java.lang.System;
  var Scanner = java.util.Scanner;
  var File = java.io.File;

  NativeRequire = (typeof NativeRequire === 'undefined') ? {} : NativeRequire;
  if (typeof require === 'function' && !NativeRequire.require) {
    NativeRequire.require = require;
  }

  function Module (id, parent, core) {
    this.id = id;
    this.core = core;
    this.parent = parent;
    this.children = [];
    this.filename = id;
    this.loaded = false;

    Object.defineProperty(this, 'exports', {
      get: function () {
        return this._exports;
      }.bind(this),
      set: function (val) {
        Require.cache[this.filename] = val;
        this._exports = val;
      }.bind(this)
    });
    this.exports = {};

    if (parent && parent.children) parent.children.push(this);

    this.require = function (id) {
      return Require(id, this);
    }.bind(this);
  }

  Module._load = function _load (file, parent, core, main) {
    var module = new Module(file, parent, core);
    var body = readFile(module.filename, module.core);
    var dir = new File(module.filename).getParent();
    var func = new Function('exports', 'module', 'require', '__filename', '__dirname', body);
    func.apply(module,
      [module.exports, module, module.require, module.filename, dir]);
    module.loaded = true;
    module.main = main;
    return module.exports;
  };

  Module.runMain = function runMain (main) {
    var file = Require.resolve(main);
    Module._load(file, undefined, false, true);
  };

  function Require (id, parent) {
    var core;
    var native_;
    var file = Require.resolve(id, parent);

    if (!file) {
      if (typeof NativeRequire.require === 'function') {
        if (Require.debug) {
          System.out.println(['Cannot resolve', id, 'defaulting to native'].join(' '));
        }
        native_ = NativeRequire.require(id);
        if (native_) return native_;
      }
      System.err.println('Cannot find module ' + id);
      throw new ModuleError('Cannot find module ' + id, 'MODULE_NOT_FOUND');
    }

    if (file.core) {
      file = file.path;
      core = true;
    }
    try {
      if (Require.cache[file]) {
        return Require.cache[file];
      } else if (file.endsWith('.js')) {
        return Module._load(file, parent, core);
      } else if (file.endsWith('.json')) {
        return loadJSON(file);
      }
    } catch (ex) {
      if (ex instanceof java.lang.Exception) {
        throw new ModuleError('Cannot load module ' + id, 'LOAD_ERROR', ex);
      } else {
        System.out.println('Cannot load module ' + id + ' LOAD_ERROR');
        throw ex;
      }
    }
  }

  Require.resolve = function (id, parent) {
    var roots = findRoots(parent);
    for (var i = 0; i < roots.length; ++i) {
      var root = roots[i];
      var result = resolveCoreModule(id, root) ||
      resolveAsFile(id, root, '.js') ||
      resolveAsFile(id, root, '.json') ||
      resolveAsDirectory(id, root) ||
      resolveAsNodeModule(id, root);
      if (result) {
        return result;
      }
    }
    return false;
  };

  Require.root = System.getProperty('user.dir');
  Require.NODE_PATH = undefined;

  function findRoots (parent) {
    var r = [];
    r.push(findRoot(parent));
    return r.concat(Require.paths());
  }

  function parsePaths (paths) {
    if (!paths) {
      return [];
    }
    if (paths === '') {
      return [];
    }
    var osName = java.lang.System.getProperty('os.name').toLowerCase();
    var separator;

    if (osName.indexOf('win') >= 0) {
      separator = ';';
    } else {
      separator = ':';
    }

    return paths.split(separator);
  }

  Require.paths = function () {
    var r = [];
    r.push(java.lang.System.getProperty('user.home') + '/.node_modules');
    r.push(java.lang.System.getProperty('user.home') + '/.node_libraries');

    if (Require.NODE_PATH) {
      r = r.concat(parsePaths(Require.NODE_PATH));
    } else {
      var NODE_PATH = java.lang.System.getenv().NODE_PATH;
      if (NODE_PATH) {
        r = r.concat(parsePaths(NODE_PATH));
      }
    }
    // r.push( $PREFIX + "/node/library" )
    return r;
  };

  function findRoot (parent) {
    if (!parent || !parent.id) { return Require.root; }
    var pathParts = parent.id.split(/[\/|\\,]+/g);
    pathParts.pop();
    return pathParts.join('/');
  }

  Require.debug = true;
  Require.cache = {};
  Require.extensions = {};
  require = Require;

  module.exports = Module;

  function loadJSON (file) {
    var json = JSON.parse(readFile(file));
    Require.cache[file] = json;
    return json;
  }

  function resolveAsNodeModule (id, root) {
    var base = [root, 'node_modules'].join('/');
    return resolveAsFile(id, base) ||
      resolveAsDirectory(id, base) ||
      (root ? resolveAsNodeModule(id, new File(root).getParent()) : false);
  }

  function resolveAsDirectory (id, root) {
    var base = [root, id].join('/');
    var file = new File([base, 'package.json'].join('/'));
    if (file.exists()) {
      try {
        var body = readFile(file.getCanonicalPath());
        var package_ = JSON.parse(body);
        if (package_.main) {
          return (resolveAsFile(package_.main, base) ||
            resolveAsDirectory(package_.main, base));
        }
        // if no package.main exists, look for index.js
        return resolveAsFile('index.js', base);
      } catch (ex) {
        throw new ModuleError('Cannot load JSON file', 'PARSE_ERROR', ex);
      }
    }
    return resolveAsFile('index.js', base);
  }

  function resolveAsFile (id, root, ext) {
    var file;
    if (id.length > 0 && id[0] === '/') {
      file = new File(normalizeName(id, ext));
      if (!file.exists()) {
        return resolveAsDirectory(id);
      }
    } else {
      file = new File([root, normalizeName(id, ext)].join('/'));
    }
    if (file.exists()) {
      return file.getCanonicalPath();
    }
  }

  function resolveCoreModule (id, root) {
    var name = normalizeName(id);
    var classloader = java.lang.Thread.currentThread().getContextClassLoader();
    if (classloader.getResource(name)) {
      return { path: name, core: true };
    }
  }

  function normalizeName (fileName, ext) {
    var extension = ext || '.js';
    if (fileName.endsWith(extension)) {
      return fileName;
    }
    return fileName + extension;
  }

  function readFile (filename, core) {
    var input;
    try {
      if (core) {
        var classloader = java.lang.Thread.currentThread().getContextClassLoader();
        input = classloader.getResourceAsStream(filename);
      } else {
        input = new File(filename);
      }
      // TODO: I think this is not very efficient
      return new Scanner(input).useDelimiter('\\A').next();
    } catch (e) {
      throw new ModuleError('Cannot read file [' + input + ']: ', 'IO_ERROR', e);
    }
  }

  function ModuleError (message, code, cause) {
    this.code = code || 'UNDEFINED';
    this.message = message || 'Error loading module';
    this.cause = cause;
  }

  // Helper function until ECMAScript 6 is complete
  if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function (suffix) {
      if (!suffix) return false;
      return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
  }

  ModuleError.prototype = new Error();
  ModuleError.prototype.constructor = ModuleError;
}());


================================================
FILE: src/test/javascript/specs/lib/a_package/index.js
================================================
var fileModule = require('file_module');
var pkgModule = require('pkg_module');

module.exports.parent_test = require('./lib/parent');
module.exports.file_module = fileModule;
module.exports.pkg_module = pkgModule;


================================================
FILE: src/test/javascript/specs/lib/a_package/lib/parent.js
================================================
var parent = module.parent;

var mod = require('dep_module');

module.exports.parentChanged = parent !== module.parent;


================================================
FILE: src/test/javascript/specs/lib/cheese/lib/index.js
================================================
module.exports.flavor = 'nacho';


================================================
FILE: src/test/javascript/specs/lib/cheese/package.json
================================================
{
  "main": "./lib"
}


================================================
FILE: src/test/javascript/specs/lib/cyclic/a.js
================================================
var b = require('./b');
module.exports = {
  fromA: 'Hello from A',
};



================================================
FILE: src/test/javascript/specs/lib/cyclic/b.js
================================================
var a = require('./a');
module.exports = {
  fromB: 'Hello from B',
};



================================================
FILE: src/test/javascript/specs/lib/cyclic/index.js
================================================
module.exports = {
  a: require('./a'),
  b: require('./b')
};



================================================
FILE: src/test/javascript/specs/lib/cyclic2/stream.js
================================================


module.exports = Stream;

function Stream() {

}

var Readable = require( 'stream_readable.js' );

Stream.Readable = Readable;

================================================
FILE: src/test/javascript/specs/lib/cyclic2/stream_readable.js
================================================

module.exports = Readable;

var Stream = require('stream.js');

Readable.Stream = Stream

function Readable() {
}


================================================
FILE: src/test/javascript/specs/lib/isolation/module-a.js
================================================

var doNotLeak = "swiss";
doLeak = "cheddar";

var b = require( 'module-b.js' );

================================================
FILE: src/test/javascript/specs/lib/isolation/module-b.js
================================================

var mine = doLeak;

expect(mine).toBe("cheddar");

try {
  mine = doNotLeak
  // should have thrown a ref-error
  expect(false).toBe(true);
} catch (err) {
  expect(err instanceof ReferenceError).toBe(true);
}

================================================
FILE: src/test/javascript/specs/lib/isolation/module-c.js
================================================

function doNotLeak() {
}

var b = require( 'module-d.js' );

================================================
FILE: src/test/javascript/specs/lib/isolation/module-d.js
================================================

try {
  var mine = doNotLeak;
  // should have thrown a reference error
  expect(false).toBe(true);
} catch (err) {
  expect(err instanceof ReferenceError).toBe(true);
}



================================================
FILE: src/test/javascript/specs/lib/mod_exports.js
================================================
exports.data = "Hello!";


================================================
FILE: src/test/javascript/specs/lib/my_package/index.js
================================================
module.exports = {
  data: "Hello!"
};


================================================
FILE: src/test/javascript/specs/lib/native_test_module.js
================================================
module.exports = "Foo!";


================================================
FILE: src/test/javascript/specs/lib/other_package/lib/foo.js
================================================
module.exports.flavor = "cool ranch";
module.exports.subdir = require('./subdir/bar').dirname;


================================================
FILE: src/test/javascript/specs/lib/other_package/lib/subdir/bar.js
================================================
module.exports.dirname = __dirname;


================================================
FILE: src/test/javascript/specs/lib/other_package/package.json
================================================
{
  "main": "lib/foo"
}


================================================
FILE: src/test/javascript/specs/lib/outer.js
================================================
var inner = require('./sub/inner');

module.exports = {
  quadruple: function(val) { return 2*inner.double(val); },
  children: module.children,
  filename: module.filename,
  innerParent: inner.parent,
};


================================================
FILE: src/test/javascript/specs/lib/simple_module.js
================================================
module.exports = {
  dirname: __dirname,
  filename: __filename,
};

function privateFunction() {}


================================================
FILE: src/test/javascript/specs/lib/some_data.json
================================================
{
  "description": "This is a JSON file",
  "data": [1,2,3]
}



================================================
FILE: src/test/javascript/specs/lib/sub/inner.js
================================================
module.exports = {
  double: function(x) { return 2*x; },
  parent: module.parent
};



================================================
FILE: src/test/javascript/specs/lib/throws.js
================================================
// This module should throw a ReferenceError
//

var foo = bar;


================================================
FILE: src/test/javascript/specs/requireSpec.js
================================================
/**
 *  Copyright 2014 Lance Ball
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
// Make the native require function look in our local directory
// for modules loaded with NativeRequire.require()

var cwd = [java.lang.System.getProperty('user.dir'),
           'src/test/javascript/specs'].join('/');

var home = java.lang.System.getProperty('user.home');

require.pushLoadPath(cwd);

// Load the NPM module loader into the global scope
load('src/main/javascript/jvm-npm.js');

// Tell require where it's root is
require.root = cwd;


beforeEach(function() {
  require.cache = [];
});

describe("NativeRequire", function() {

  it("should be a global object", function(){
    expect(typeof NativeRequire).toBe('object');
  });

  it("should expose DynJS' builtin require() function", function(){
    expect(typeof NativeRequire.require).toBe('function');
    var f = NativeRequire.require('./lib/native_test_module');
    expect(f).toBe("Foo!");
    expect(NativeRequire.require instanceof org.dynjs.runtime.builtins.Require)
      .toBe(true);
  });

  it("should fall back to builtin require() if not found", function() {
    var called = false;
    NativeRequire.require = function() {
      called = true;
      return "Got native module";
    };
    var native = require('not_found');
    expect(native).toBe("Got native module");
    expect(called).toBe(true);
  });

});

describe("NPM global require()", function() {

  it("should be a function", function() {
    expect(typeof require).toBe('function');
  });

  it("should have a resolve() property that is a function", function() {
    expect(typeof require.resolve).toBe('function');
  });

  it("should have a cache property that is an Object", function() {
    expect(typeof require.cache).toBe('object');
  });

  it("should have an extensions property that is an Object", function() {
    expect(typeof require.extensions).toBe('object');
  });

  it("should find and load files with a .js extension", function() {
    // Ensure that the npm require() is not using NativeRequire
    var that=this;
    NativeRequire.require = function() {
      that.fail("NPM require() should not use DynJS native require");
    };
    expect(require('./lib/native_test_module')).toBe("Foo!");
  });

  it("should throw an Error if a file can't be found", function() {
    expect(function() {require('./not_found.js');}).toThrow(new Error('Cannot find module ./not_found.js'));
    try {
      require('./not_found.js');
    } catch(e) {
      expect(e.code).toBe('MODULE_NOT_FOUND');
    }
  });

  it("should not wrap errors encountered when loading a module", function() {
    try {
      require('./lib/throws');
    } catch(ex) {
      print(ex);
      expect(ex instanceof ReferenceError).toBeTruthy();
    }
  });

  it("should support nested requires", function() {
    var outer = require('./lib/outer');
    expect(outer.quadruple(2)).toBe(8);
  });

  it("should support an ID with an extension", function() {
    var outer = require('./lib/outer.js');
    expect(outer.quadruple(2)).toBe(8);
  });

  it("should return the a .json file as a JSON object", function() {
    var json = require('./lib/some_data.json');
    expect(json.description).toBe("This is a JSON file");
    expect(json.data).toEqual([1,2,3]);
  });

  it("should cache modules in require.cache", function() {
    var outer = require('./lib/outer.js');
    expect(outer).toBe(require.cache[outer.filename]);
    var outer2 = require('./lib/outer.js');
    expect(outer2).toBe(outer);
  });

  it("should handle cyclic dependencies", function() {
    var main = require('./lib/cyclic');
    expect(main.a.fromA).toBe('Hello from A');
    expect(main.b.fromB).toBe('Hello from B');
  });

  describe("folders as modules", function() {
    it("should find package.json in a module folder", function() {
      var package = require('./lib/other_package');
      expect(package.flavor).toBe('cool ranch');
      expect(package.subdir).toBe([cwd, 'lib/other_package/lib/subdir'].join('/'));
    });

    it('should load package.json main property even if it is a directory', function() {
      var cheese = require('./lib/cheese');
      expect(cheese.flavor).toBe('nacho');
    });

    it("should find index.js in a directory, if no package.json exists", function() {
      var package = require('./lib/my_package');
      expect(package.data).toBe('Hello!');
    });
  });

  describe("node_modules folders", function() {

    it("should load file modules from the node_modules folder in cwd", function() {
      var top = require('./lib/a_package');
      expect(top.file_module).toBe('Hello from a file module');
    });

    it("should load package modules from the node_modules folder", function() {
      var top = require('./lib/a_package');
      expect(top.pkg_module.pkg).toBe('Hello from a package module');
    });

    it("should find node_module packages in the parent path", function() {
      var top = require('./lib/a_package');
      expect(top.pkg_module.file).toBe('Hello from a file module');
    });

    it("should find node_module packages from a sibling path", function() {
      var top = require('./lib/a_package');
      expect(top.parent_test.parentChanged).toBe(false);
    });

    it('should find node_module packages all the way up above cwd', function() {
      var m = require('root_module');
      expect(m.message).toBe('You are at the root');
    });

  });

});

describe("NPM Module execution context", function() {

  it("should have a __dirname property", function() {
    var top = require('./lib/simple_module');
    expect(top.dirname).toBe([cwd, 'lib'].join('/'));
  });

  it("should have a __filename property", function() {
    var top = require('./lib/simple_module');
    expect(top.filename).toBe([cwd, 'lib/simple_module.js'].join('/'));
  });

  it("should not expose private module functions globally", function() {
    var top = require('./lib/simple_module');
    expect(top.privateFunction).toBe(undefined);
  });

  it("should have a parent property", function() {
    var outer = require('./lib/outer');
    expect(outer.innerParent.id).toBe([cwd, 'lib/outer.js'].join('/'));
  });

  it("should have a filename property", function() {
    var outer = require('./lib/outer');
    expect(outer.filename).toBe([cwd, 'lib/outer.js'].join('/'));
  });

  it("should have a children property", function() {
    var outer = require('./lib/outer');
    expect(outer.children.length).toBe(1);
    expect(outer.children[0].id).toBe([cwd, 'lib/sub/inner.js'].join('/'));
  });

  it("should support setting the 'free' exports variable", function() {
    var modExports = require('./lib/mod_exports');
    expect(modExports.data).toBe("Hello!");
  });

});

describe("module isolation", function() {
  it("should expose global variables and not expose 'var' declared variables", function() {
    var top = require( './lib/isolation/module-a.js');
    expect(doLeak).toBe("cheddar");
    try {
      var shouldFail = doNotLeak;
      // should have thrown
      expect(true).toBe(false);
    } catch (err) {
      expect( err instanceof ReferenceError ).toBe(true);
    }
  });

  it("should not leak function declarations", function() {
    var top = require('./lib/isolation/module-c.js');
    try {
      var shouldFail = doNotLeak;
      // should have thrown
      expect(true).toBe(false);
    } catch (err) {
      expect( err instanceof ReferenceError ).toBe(true);
    }
  });
});

describe("cyclic with replacement of module.exports", function() {
  it( "should have the same sense of an object in all places", function() {
    var Stream = require( "./lib/cyclic2/stream.js" );

    expect( typeof Stream ).toBe( "function"  );
    expect( typeof Stream.Readable ).toBe( "function" );
    expect( typeof Stream.Readable.Stream ).toBe( "function" );

  });
});

describe("Core modules", function() {
  it("should be found on the classpath", function() {
    var core = require('core');
    expect(core).not.toBeFalsy();
  });

  it( "should have the same sense of an object in all places", function() {
    var Core = require( "core.js" );

    expect( typeof Core ).toBe( "function"  );
    expect( typeof Core.Child ).toBe( "function" );
    expect( typeof Core.Child.Core ).toBe( "function" );

  });
});

describe("Path management", function() {
  it( "should respect NODE_PATH variable", function() {
    require.NODE_PATH = 'foo:bar';
    var results = require.paths();
    expect( results[0] ).toBe( home + "/.node_modules" );
    expect( results[1] ).toBe( home + "/.node_libraries" );
    expect( results[2] ).toBe( 'foo' );
    expect( results[3] ).toBe( 'bar' );
    //java.lang.System.err.println( results );

  });
});

describe("The Module module", function() {
  it('should exist', function() {
    var Module = require('jvm-npm');
    expect(Module).toBeTruthy();
  });

  it('should have a runMain function', function() {
    var Module = require('jvm-npm');
    expect(typeof Module.runMain).toBe('function');
  });
});


================================================
FILE: src/test/resources/_core.js
================================================

module.exports = Child;

var Core = require('core');

Child.Core = Core;

function Child() {
}


================================================
FILE: src/test/resources/core.js
================================================


module.exports = Core;

function Core() {

}

var Child = require( '_core' );

Core.Child = Child;
Download .txt
gitextract_3ejd1flu/

├── .eslintrc.json
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── examples/
│   ├── simple/
│   │   ├── app.js
│   │   └── my-module.js
│   └── underscore/
│       ├── README.md
│       ├── app.js
│       └── package.json
├── package.json
├── pom.xml
└── src/
    ├── main/
    │   └── javascript/
    │       └── jvm-npm.js
    └── test/
        ├── javascript/
        │   └── specs/
        │       ├── lib/
        │       │   ├── a_package/
        │       │   │   ├── index.js
        │       │   │   └── lib/
        │       │   │       └── parent.js
        │       │   ├── cheese/
        │       │   │   ├── lib/
        │       │   │   │   └── index.js
        │       │   │   └── package.json
        │       │   ├── cyclic/
        │       │   │   ├── a.js
        │       │   │   ├── b.js
        │       │   │   └── index.js
        │       │   ├── cyclic2/
        │       │   │   ├── stream.js
        │       │   │   └── stream_readable.js
        │       │   ├── isolation/
        │       │   │   ├── module-a.js
        │       │   │   ├── module-b.js
        │       │   │   ├── module-c.js
        │       │   │   └── module-d.js
        │       │   ├── mod_exports.js
        │       │   ├── my_package/
        │       │   │   └── index.js
        │       │   ├── native_test_module.js
        │       │   ├── other_package/
        │       │   │   ├── lib/
        │       │   │   │   ├── foo.js
        │       │   │   │   └── subdir/
        │       │   │   │       └── bar.js
        │       │   │   └── package.json
        │       │   ├── outer.js
        │       │   ├── simple_module.js
        │       │   ├── some_data.json
        │       │   ├── sub/
        │       │   │   └── inner.js
        │       │   └── throws.js
        │       └── requireSpec.js
        └── resources/
            ├── _core.js
            └── core.js
Download .txt
SYMBOL INDEX (20 symbols across 8 files)

FILE: examples/underscore/app.js
  function example (line 42) | function example(name, ex) {

FILE: src/main/javascript/jvm-npm.js
  function Module (line 31) | function Module (id, parent, core) {
  function Require (line 74) | function Require (id, parent) {
  function findRoots (line 132) | function findRoots (parent) {
  function parsePaths (line 138) | function parsePaths (paths) {
  function findRoot (line 174) | function findRoot (parent) {
  function loadJSON (line 188) | function loadJSON (file) {
  function resolveAsNodeModule (line 194) | function resolveAsNodeModule (id, root) {
  function resolveAsDirectory (line 201) | function resolveAsDirectory (id, root) {
  function resolveAsFile (line 221) | function resolveAsFile (id, root, ext) {
  function resolveCoreModule (line 236) | function resolveCoreModule (id, root) {
  function normalizeName (line 244) | function normalizeName (fileName, ext) {
  function readFile (line 252) | function readFile (filename, core) {
  function ModuleError (line 268) | function ModuleError (message, code, cause) {

FILE: src/test/javascript/specs/lib/cyclic2/stream.js
  function Stream (line 5) | function Stream() {

FILE: src/test/javascript/specs/lib/cyclic2/stream_readable.js
  function Readable (line 8) | function Readable() {

FILE: src/test/javascript/specs/lib/isolation/module-c.js
  function doNotLeak (line 2) | function doNotLeak() {

FILE: src/test/javascript/specs/lib/simple_module.js
  function privateFunction (line 6) | function privateFunction() {}

FILE: src/test/resources/_core.js
  function Child (line 8) | function Child() {

FILE: src/test/resources/core.js
  function Core (line 5) | function Core() {
Condensed preview — 41 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".eslintrc.json",
    "chars": 534,
    "preview": "{\n  \"extends\": \"semistandard\",\n  \"globals\": {\n    \"java\": false,\n    \"NativeRequire\": true\n  },\n  \"rules\": {\n    \"no-glo"
  },
  {
    "path": ".gitignore",
    "chars": 38,
    "preview": "target\nnode_modules\n.idea\n*.iml\n*.log\n"
  },
  {
    "path": ".travis.yml",
    "chars": 181,
    "preview": "sudo: required\ndist: trusty\nlanguage: java\njdk:\n  - openjdk8\nbefore_script:\nscript:\n   - make ci\nbranches:\n  only:\n    -"
  },
  {
    "path": "LICENSE",
    "chars": 559,
    "preview": "Copyright 2014-2016 Red Hat, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this "
  },
  {
    "path": "Makefile",
    "chars": 167,
    "preview": "ci: test\n\ntest: lint\n\tnpm run test\n\nlint: node_modules\n\tnpm run lint\n\nclean:\n\trm -rf node_modules target\n\nnode_modules: "
  },
  {
    "path": "README.md",
    "chars": 1278,
    "preview": "# jvm-npm\n\nSupport for NPM module loading in Javascript runtimes on the JVM.\nImplementation is based on http://nodejs.or"
  },
  {
    "path": "examples/simple/app.js",
    "chars": 97,
    "preview": "load('../../src/main/javascript/jvm-npm.js');\nvar hello = require('./my-module');\nhello('Bob!');\n"
  },
  {
    "path": "examples/simple/my-module.js",
    "chars": 96,
    "preview": "module.exports = function sayHello(name) {\n  java.lang.System.out.println(\"Hello \" + name);\n};\n\n"
  },
  {
    "path": "examples/underscore/README.md",
    "chars": 422,
    "preview": "# Example: underscore.js\n\nTo run the example, you should have either dynjs or jrunscript\n(Nashorn) in your PATH. And you"
  },
  {
    "path": "examples/underscore/app.js",
    "chars": 960,
    "preview": "load('../../src/main/javascript/jvm-npm.js');\nvar _ = require('underscore');\n\nprint('Here we do some stuff with undersco"
  },
  {
    "path": "examples/underscore/package.json",
    "chars": 198,
    "preview": "{\n  \"name\": \"jvm-npm-underscore\",\n  \"description\": \"example application using underscore.js on the JVM\",\n  \"version\": \"0"
  },
  {
    "path": "package.json",
    "chars": 1111,
    "preview": "{\n  \"name\": \"jvm-npm\",\n  \"version\": \"0.1.1\",\n  \"description\": \"Support for NPM module loading in Javascript runtimes on "
  },
  {
    "path": "pom.xml",
    "chars": 5150,
    "preview": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-ins"
  },
  {
    "path": "src/main/javascript/jvm-npm.js",
    "chars": 8128,
    "preview": "/**\n *  Copyright 2014-2016 Red Hat, Inc.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\")\n *  you "
  },
  {
    "path": "src/test/javascript/specs/lib/a_package/index.js",
    "chars": 215,
    "preview": "var fileModule = require('file_module');\nvar pkgModule = require('pkg_module');\n\nmodule.exports.parent_test = require('."
  },
  {
    "path": "src/test/javascript/specs/lib/a_package/lib/parent.js",
    "chars": 120,
    "preview": "var parent = module.parent;\n\nvar mod = require('dep_module');\n\nmodule.exports.parentChanged = parent !== module.parent;\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cheese/lib/index.js",
    "chars": 33,
    "preview": "module.exports.flavor = 'nacho';\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cheese/package.json",
    "chars": 22,
    "preview": "{\n  \"main\": \"./lib\"\n}\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cyclic/a.js",
    "chars": 72,
    "preview": "var b = require('./b');\nmodule.exports = {\n  fromA: 'Hello from A',\n};\n\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cyclic/b.js",
    "chars": 72,
    "preview": "var a = require('./a');\nmodule.exports = {\n  fromB: 'Hello from B',\n};\n\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cyclic/index.js",
    "chars": 64,
    "preview": "module.exports = {\n  a: require('./a'),\n  b: require('./b')\n};\n\n"
  },
  {
    "path": "src/test/javascript/specs/lib/cyclic2/stream.js",
    "chars": 128,
    "preview": "\n\nmodule.exports = Stream;\n\nfunction Stream() {\n\n}\n\nvar Readable = require( 'stream_readable.js' );\n\nStream.Readable = R"
  },
  {
    "path": "src/test/javascript/specs/lib/cyclic2/stream_readable.js",
    "chars": 115,
    "preview": "\nmodule.exports = Readable;\n\nvar Stream = require('stream.js');\n\nReadable.Stream = Stream\n\nfunction Readable() {\n}\n"
  },
  {
    "path": "src/test/javascript/specs/lib/isolation/module-a.js",
    "chars": 80,
    "preview": "\nvar doNotLeak = \"swiss\";\ndoLeak = \"cheddar\";\n\nvar b = require( 'module-b.js' );"
  },
  {
    "path": "src/test/javascript/specs/lib/isolation/module-b.js",
    "chars": 210,
    "preview": "\nvar mine = doLeak;\n\nexpect(mine).toBe(\"cheddar\");\n\ntry {\n  mine = doNotLeak\n  // should have thrown a ref-error\n  expec"
  },
  {
    "path": "src/test/javascript/specs/lib/isolation/module-c.js",
    "chars": 60,
    "preview": "\nfunction doNotLeak() {\n}\n\nvar b = require( 'module-d.js' );"
  },
  {
    "path": "src/test/javascript/specs/lib/isolation/module-d.js",
    "chars": 172,
    "preview": "\ntry {\n  var mine = doNotLeak;\n  // should have thrown a reference error\n  expect(false).toBe(true);\n} catch (err) {\n  e"
  },
  {
    "path": "src/test/javascript/specs/lib/mod_exports.js",
    "chars": 25,
    "preview": "exports.data = \"Hello!\";\n"
  },
  {
    "path": "src/test/javascript/specs/lib/my_package/index.js",
    "chars": 39,
    "preview": "module.exports = {\n  data: \"Hello!\"\n};\n"
  },
  {
    "path": "src/test/javascript/specs/lib/native_test_module.js",
    "chars": 25,
    "preview": "module.exports = \"Foo!\";\n"
  },
  {
    "path": "src/test/javascript/specs/lib/other_package/lib/foo.js",
    "chars": 95,
    "preview": "module.exports.flavor = \"cool ranch\";\nmodule.exports.subdir = require('./subdir/bar').dirname;\n"
  },
  {
    "path": "src/test/javascript/specs/lib/other_package/lib/subdir/bar.js",
    "chars": 36,
    "preview": "module.exports.dirname = __dirname;\n"
  },
  {
    "path": "src/test/javascript/specs/lib/other_package/package.json",
    "chars": 24,
    "preview": "{\n  \"main\": \"lib/foo\"\n}\n"
  },
  {
    "path": "src/test/javascript/specs/lib/outer.js",
    "chars": 206,
    "preview": "var inner = require('./sub/inner');\n\nmodule.exports = {\n  quadruple: function(val) { return 2*inner.double(val); },\n  ch"
  },
  {
    "path": "src/test/javascript/specs/lib/simple_module.js",
    "chars": 99,
    "preview": "module.exports = {\n  dirname: __dirname,\n  filename: __filename,\n};\n\nfunction privateFunction() {}\n"
  },
  {
    "path": "src/test/javascript/specs/lib/some_data.json",
    "chars": 63,
    "preview": "{\n  \"description\": \"This is a JSON file\",\n  \"data\": [1,2,3]\n}\n\n"
  },
  {
    "path": "src/test/javascript/specs/lib/sub/inner.js",
    "chars": 86,
    "preview": "module.exports = {\n  double: function(x) { return 2*x; },\n  parent: module.parent\n};\n\n"
  },
  {
    "path": "src/test/javascript/specs/lib/throws.js",
    "chars": 64,
    "preview": "// This module should throw a ReferenceError\n//\n\nvar foo = bar;\n"
  },
  {
    "path": "src/test/javascript/specs/requireSpec.js",
    "chars": 9545,
    "preview": "/**\n *  Copyright 2014 Lance Ball\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not"
  },
  {
    "path": "src/test/resources/_core.js",
    "chars": 96,
    "preview": "\nmodule.exports = Child;\n\nvar Core = require('core');\n\nChild.Core = Core;\n\nfunction Child() {\n}\n"
  },
  {
    "path": "src/test/resources/core.js",
    "chars": 101,
    "preview": "\n\nmodule.exports = Core;\n\nfunction Core() {\n\n}\n\nvar Child = require( '_core' );\n\nCore.Child = Child;\n"
  }
]

About this extraction

This page contains the full source code of the nodyn/jvm-npm GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 41 files (30.1 KB), approximately 9.2k tokens, and a symbol index with 20 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!