├── .gitignore
├── README.md
├── bin
├── .gitignore
├── activate
├── activate.bash
├── activate.cmd
├── codesign
├── js
├── json
├── narwhal
├── narwhal.cmd
├── sea
├── sea.cmd
├── tusk
└── tusk.cmd
├── catalog-2.json
├── catalog.json
├── docs
├── .gitignore
├── available-packages.md
├── browser-api-plan.md
├── browser-api.md
├── catalog.md
├── download.md
├── engines.md
├── json-tool.md
├── lib
│ ├── binary.wiki
│ ├── file.wiki
│ ├── os
│ │ └── popen.md
│ └── system.md
├── modules-advanced.md
├── modules.md
├── narwhal.md
├── packages-howto.md
├── packages-using.md
├── posts
│ └── 2009-07-29-hello-0.1.md
├── quick-start.md
├── sea.md
└── test.md
├── engines
├── .gitignore
├── browser
│ └── lib
│ │ ├── binary.js
│ │ ├── reactor.js
│ │ └── system.js
├── default
│ └── lib
│ │ ├── binary-engine.js
│ │ ├── binary.js
│ │ ├── file-engine.js
│ │ ├── global-commonjs.js
│ │ ├── global-es5.js
│ │ ├── global.js
│ │ ├── io-engine.js
│ │ ├── json.js
│ │ ├── os-engine.js
│ │ ├── reactor.js
│ │ ├── system.js
│ │ └── worker.js
├── rhino
│ ├── bin
│ │ ├── narwhal-rhino
│ │ └── narwhal-rhino.cmd
│ ├── bootstrap.js
│ ├── jars
│ │ ├── jline.jar
│ │ ├── jna.jar
│ │ └── js.jar
│ ├── lib
│ │ ├── binary-engine.js
│ │ ├── concurrency.js
│ │ ├── event-queue.js
│ │ ├── events-engine.js
│ │ ├── file-engine.js
│ │ ├── fs-base.js
│ │ ├── http-client-engine.js
│ │ ├── http-engine.js
│ │ ├── http.js
│ │ ├── interpreter.js
│ │ ├── io-engine.js
│ │ ├── md5-engine.js
│ │ ├── narwhal
│ │ │ └── tusk
│ │ │ │ └── support.js
│ │ ├── os-engine.js
│ │ ├── packages-engine.js
│ │ ├── sandbox-engine.js
│ │ ├── system.js
│ │ ├── uuid.js
│ │ ├── worker-engine.js
│ │ └── zip.js
│ └── package.json
├── secure
│ └── lib
│ │ ├── file.js
│ │ └── system.js
└── template
│ ├── bin
│ └── narwhal-engine-name
│ ├── bootstrap.js
│ └── lib
│ ├── file-engine.js
│ └── system.js
├── examples
├── browser-deployment-jackconfig.js
├── fibonacci-worker.js
├── fibonacci.js
├── hello
├── narwhal
└── not-quite-a-quine.js
├── lib
├── args.js
├── assert.js
├── base16.js
├── base64.js
├── crc32.js
├── events.js
├── file-bootstrap.js
├── file.js
├── fs-bootstrap.js
├── hash.js
├── hashp.js
├── html.js
├── http-client.js
├── http.js
├── http
│ └── fs-store.js
├── io.js
├── jsmin.js
├── jsonpath.js
├── loader.js
├── loader
│ ├── attenuated.js
│ ├── multi.js
│ └── prefix.js
├── logger.js
├── md4.js
├── md5.js
├── mime.js
├── narwhal.js
├── narwhal
│ ├── client.js
│ ├── compile.js
│ ├── env.js
│ ├── inline.js
│ ├── json.js
│ ├── json.md
│ ├── repl-worker.js
│ ├── repl.js
│ ├── server-test.js
│ ├── server.js
│ ├── tusk.js
│ └── tusk
│ │ ├── commands
│ │ ├── bin.js
│ │ ├── bundle.js
│ │ ├── catalog.js
│ │ ├── clone.js
│ │ ├── consolidate.js
│ │ ├── engine.js
│ │ ├── freeze.js
│ │ ├── init.js
│ │ ├── install.js
│ │ ├── list.js
│ │ ├── orphans.js
│ │ ├── reheat.js
│ │ ├── remove.js
│ │ ├── search.js
│ │ ├── update.js
│ │ └── upgrade.js
│ │ ├── support.js
│ │ └── update.js
├── os.js
├── packages.js
├── printf.js
├── promise.js
├── querystring.js
├── ref-send.js
├── sandbox.js
├── sha.js
├── sha256.js
├── struct.js
├── term.js
├── test.js
├── test
│ ├── assert.js
│ ├── equiv.js
│ ├── jsdump.js
│ └── runner.js
├── unload.js
├── uri.js
├── utf8.js
├── util.js
├── uuid.js
└── xregexp.js
├── local.json.template
├── narwhal.conf.template
├── narwhal.gemspec
├── narwhal.js
├── package.json
├── packages
├── .gitignore
└── readline
│ ├── engines
│ ├── default
│ │ └── lib
│ │ │ └── readline.js
│ └── rhino
│ │ └── lib
│ │ └── readline.js
│ └── package.json
├── sources.json
└── tests
├── all-tests.js
├── args.js
├── args
├── choices.js
├── domain.js
├── options.js
├── shifting.js
└── validation.js
├── base64.js
├── commonjs.js
├── commonjs
├── all-tests.js
├── assert.js
├── bytearray-encodings-tests.js
├── bytearray-tests.js
├── bytestring-encodings-tests.js
├── bytestring-tests.js
├── es5
│ ├── all-tests.js
│ ├── bind.js
│ └── date-regression.js
├── file-tests.js
├── file
│ ├── dirname.js
│ ├── extension.js
│ ├── is-absolute.js
│ ├── iterator.js
│ ├── normal.js
│ ├── path.js
│ ├── relative.js
│ └── resolve.js
├── fs-base.js
├── module-tests.js
└── modules
│ ├── absolute
│ ├── b.js
│ ├── program.js
│ ├── submodule
│ │ └── a.js
│ └── test.js
│ ├── all-tests.js
│ ├── config.js
│ ├── cyclic
│ ├── a.js
│ ├── b.js
│ ├── program.js
│ └── test.js
│ ├── determinism
│ ├── program.js
│ ├── submodule
│ │ ├── a.js
│ │ └── b.js
│ └── test.js
│ ├── exactExports
│ ├── a.js
│ ├── program.js
│ └── test.js
│ ├── hasOwnProperty
│ ├── method
│ ├── a.js
│ ├── program.js
│ └── test.js
│ ├── missing
│ ├── program.js
│ └── test.js
│ ├── monkeys
│ ├── a.js
│ ├── program.js
│ └── test.js
│ ├── nested
│ ├── a
│ │ └── b
│ │ │ └── c
│ │ │ └── d.js
│ ├── program.js
│ └── test.js
│ ├── relative
│ ├── program.js
│ ├── submodule
│ │ ├── a.js
│ │ └── b.js
│ └── test.js
│ └── transitive
│ ├── a.js
│ ├── b.js
│ ├── c.js
│ ├── program.js
│ └── test.js
├── events.js
├── file
├── all-tests.js
├── fnmatch.js
├── glob.js
└── match.js
├── global.js
├── global
├── array.js
└── date-parse.js
├── hashes.js
├── html.js
├── interpreter.js
├── io
├── all-tests.js
├── stringio.js
└── textinputstream.js
├── os
├── all-tests.js
├── parse-fuzzer.js
├── parse.js
├── popen.js
└── system.js
├── package
├── _files
│ └── test-sea
│ │ ├── lib
│ │ └── main.js
│ │ ├── package.json
│ │ ├── packages
│ │ ├── test-package-1
│ │ │ ├── lib
│ │ │ └── package.json
│ │ └── test-package-2
│ │ │ ├── lib
│ │ │ └── package.json
│ │ └── using
│ │ └── domain.com
│ │ └── path
│ │ └── to
│ │ ├── catalog
│ │ └── package2
│ │ │ ├── lib
│ │ │ └── package.json
│ │ └── package1
│ │ ├── lib
│ │ └── package.json
└── using.js
├── printf.js
├── query-string.js
├── sandbox
├── byte-io.js
├── fileName.js
├── foo.js
└── reload.js
├── uri.js
└── util
├── all-tests.js
├── array.js
├── array
├── is-arguments.js
└── is-array-like.js
├── case.js
├── collection.js
├── complete.js
├── eq.js
├── expand.js
├── object.js
├── operator.js
├── range.js
├── repr.js
├── string.js
├── unique.js
└── update.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .tusk
2 | README.html
3 | local.json
4 | narwhal.conf
5 | zips
6 | .DS_Store
7 | ._*
8 | /build
9 | /.tmp
10 | gh-pages
11 | Makefile
12 |
--------------------------------------------------------------------------------
/bin/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 | !activate
4 | !activate.bash
5 | !activate.cmd
6 | !js
7 | !js.cmd
8 | !json
9 | !narwhal
10 | !narwhal.cmd
11 | !sea
12 | !sea.cmd
13 | !tusk
14 | !tusk.cmd
15 | !codesign
16 |
--------------------------------------------------------------------------------
/bin/activate:
--------------------------------------------------------------------------------
1 | activate.bash
--------------------------------------------------------------------------------
/bin/activate.bash:
--------------------------------------------------------------------------------
1 |
2 | if [ -z "${BASH_ARGV[0]}" ]; then
3 |
4 | # as a last recourse, use the present working directory
5 | PACKAGE_HOME=$(pwd)
6 |
7 | else
8 |
9 | # get the absolute path of the executable
10 | SELF_PATH=$(
11 | cd -P -- "$(dirname -- "${BASH_ARGV[0]}")" \
12 | && pwd -P
13 | ) && SELF_PATH=$SELF_PATH/$(basename -- "${BASH_ARGV[0]}")
14 |
15 | # resolve symlinks
16 | while [ -h "$SELF_PATH" ]; do
17 | DIR=$(dirname -- "$SELF_PATH")
18 | SYM=$(readlink -- "$SELF_PATH")
19 | SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
20 | done
21 |
22 | PACKAGE_HOME=$(dirname -- "$(dirname -- "$SELF_PATH")")
23 |
24 | fi
25 |
26 | export PACKAGE_HOME
27 |
28 | # which -s narwhal doesn't work (os x 10.5, kriskowal)
29 | if [ -f "$PACKAGE_HOME"/bin/narwhal ]; then
30 | NARWHAL="$PACKAGE_HOME"/bin/narwhal
31 | elif [ -f "$PACKAGE_HOME"/packages/narwhal/bin/narwhal ]; then
32 | NARWHAL="$PACKAGE_HOME"/packages/narwhal/bin/narwhal
33 | else
34 | env narwhal -e '' >/dev/null 2>&1
35 | if [ "$?" -ne 127 ]; then
36 | NARWHAL=narwhal
37 | else
38 | echo "ERROR: narwhal is not in your PATH nor in $PACKAGE_HOME/bin." >&2
39 | fi
40 | fi
41 |
42 | if [ -f "$PACKAGE_HOME"/narwhal.conf ]; then
43 | source "$PACKAGE_HOME"/narwhal.conf
44 | export NARWHAL_DEFAULT_ENGINE
45 | fi
46 |
47 | if [ "$NARWHAL" ]; then
48 | # try to get the PATH for Narwhal packages. Print a warning if it fails.
49 | PATH_NEW="$("$NARWHAL" --package "$PACKAGE_HOME" --path :)"
50 | if [ "$?" -ne 0 ]; then
51 | echo "Warning: Unable to setup PATH for Narwhal." 1>&2
52 | else
53 | export PATH="$PATH_NEW"
54 | fi
55 | fi
56 |
57 |
--------------------------------------------------------------------------------
/bin/activate.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | set PATH=%~dp0;%PATH%
4 |
--------------------------------------------------------------------------------
/bin/codesign:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | GITHUB_USER_NAME=$1
3 | FIRST_NAME=$2
4 | LAST_NAME=$3
5 | cat | while read FILE_NAME; do
6 | cat "$FILE_NAME" \
7 | | sed "s/^"'\/\/'" -- $1.*/"'\/\/'" -- $*/" \
8 | | sed "s/^"'\/\/'" -- $2 $3.*/"'\/\/'" -- $*/" \
9 | > "$FILE_NAME.$1"
10 | mv "$FILE_NAME.$1" "$FILE_NAME"
11 | done
12 |
--------------------------------------------------------------------------------
/bin/js:
--------------------------------------------------------------------------------
1 | narwhal
--------------------------------------------------------------------------------
/bin/json:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 | require("narwhal/json").main(system);
3 |
--------------------------------------------------------------------------------
/bin/narwhal:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # get the absolute path of the executable
4 | SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH="$SELF_PATH/$(basename -- "$0")"
5 |
6 | # resolve symlinks
7 | while [ -h "$SELF_PATH" ]; do
8 | DIR=$(dirname -- "$SELF_PATH")
9 | SYM=$(readlink -- "$SELF_PATH")
10 | SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
11 | done
12 |
13 | # NARWHAL_HOME is the 2nd ancestor directory of this shell script
14 | NARWHAL_HOME=$(dirname -- "$(dirname -- "$SELF_PATH")")
15 |
16 | # use Rhino as the default if none is specified in narwhal.conf
17 | NARWHAL_DEFAULT_ENGINE="rhino"
18 |
19 | # load narwhal.conf if it exists
20 | if [ -f "$NARWHAL_HOME/narwhal.conf" ]; then
21 | source "$NARWHAL_HOME"/narwhal.conf
22 | fi
23 |
24 | # load narwhal.local.conf in pwd if it exists
25 | if [ -f "narwhal.local.conf" ]; then
26 | source "narwhal.local.conf"
27 | fi
28 |
29 | if [ -n "$NARWHAL_DEBUG" ]; then
30 | export NARWHAL_DEBUG
31 | fi
32 |
33 | # if NARWHAL_ENGINE isn't yet set, set it to the default engine, and export it
34 | if [ -z "$NARWHAL_ENGINE" ]; then
35 | NARWHAL_ENGINE=$NARWHAL_DEFAULT_ENGINE
36 | fi
37 | export NARWHAL_HOME
38 |
39 | # build the executable name for the engine
40 | EXECUTABLE_NAME="narwhal-$NARWHAL_ENGINE"
41 |
42 | # search for the engine home directory
43 | # try narwhal.conf setting
44 | if [ "$NARWHAL_ENGINE_HOME" ]; then
45 | export NARWHAL_ENGINE_HOME=$(cd -P -- "$NARWHAL_HOME" && cd -P -- "$NARWHAL_ENGINE_HOME" && pwd -P)
46 | # try relative, engines
47 | elif [ -f "$NARWHAL_HOME/engines/$NARWHAL_ENGINE/bin/$EXECUTABLE_NAME" ]; then
48 | export NARWHAL_ENGINE_HOME="$NARWHAL_HOME/engines/$NARWHAL_ENGINE"
49 | # try relative, packages
50 | elif [ -f "$NARWHAL_HOME/packages/narwhal-$NARWHAL_ENGINE/bin/$EXECUTABLE_NAME" ]; then
51 | export NARWHAL_ENGINE_HOME="$NARWHAL_HOME/packages/narwhal-$NARWHAL_ENGINE"
52 | # try $PATH
53 | elif which -s "$EXECUTABLE_NAME"; then
54 | EXECUTABLE_PATH=$(which "$EXECUTABLE_NAME")
55 | # resolve symlinks
56 | while [ -h "$EXECUTABLE_PATH" ]; do
57 | DIR=$(dirname -- "$EXECUTABLE_PATH")
58 | SYM=$(readlink -- "$EXECUTABLE_PATH")
59 | EXECUTABLE_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
60 | done
61 | export NARWHAL_ENGINE_HOME=$(dirname -- "$(dirname -- "$EXECUTABLE_PATH")")
62 | else
63 | echo "Can't find executable for $NARWHAL_ENGINE"
64 | exit 1
65 | fi
66 |
67 | exec "$NARWHAL_ENGINE_HOME"/bin/"$EXECUTABLE_NAME" "$@"
68 |
--------------------------------------------------------------------------------
/bin/narwhal.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 |
4 | :: NARWHAL_HOME is the parent of the bin directory
5 | set NARWHAL_HOME=%~dp0..
6 |
7 | :: use Rhino as the default if none is specified in narwhal.conf
8 | set NARWHAL_DEFAULT_ENGINE=rhino
9 |
10 | :: load narwhal.conf if it exists
11 | :: TODO: Doesn't fully mimicks the linux `source` command,
12 | :: but should be enough for loading narwhal.conf
13 | if exist "%NARWHAL_HOME%\narwhal.conf" (
14 | for /f "eol=# tokens=1,2 delims==" %%i in (%NARWHAL_HOME%\narwhal.conf) do set %%i=%%j
15 | )
16 |
17 | :: if NARWHAL_ENGINE isn't yet set, set it to the default engine, and export it
18 | if not defined NARWHAL_ENGINE (
19 | set NARWHAL_ENGINE=%NARWHAL_DEFAULT_ENGINE%
20 | )
21 |
22 | :: build the executable name for the engine
23 | set EXECUTABLE_NAME=narwhal-%NARWHAL_ENGINE%.cmd
24 |
25 | :: search for the engine home directory
26 | :: TODO: look for more, including ".exe"?
27 | if exist "%NARWHAL_HOME%\engines\%NARWHAL_ENGINE%." (
28 | set NARWHAL_ENGINE_HOME=%NARWHAL_HOME%\engines\%NARWHAL_ENGINE%
29 | ) else (
30 | echo Can't find executable for %NARWHAL_ENGINE%
31 | exit /b 1
32 | )
33 |
34 | call "%NARWHAL_ENGINE_HOME%\bin\%EXECUTABLE_NAME%" %*
35 |
--------------------------------------------------------------------------------
/bin/sea:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # this script is intended to work both in narwhal/bin and in
4 | # any project's bin dir; it's copied by tusk --init.
5 |
6 | function enquote_all () {
7 | ARGS=""
8 | for ARG in "$@"; do
9 | [ -n "$ARGS" ] && ARGS="$ARGS "
10 | ARGS="$ARGS'""$(echo " $ARG" | cut -c 2- | sed 's/'"'"'/'"'"'"'"'"'"'"'"'/g')""'"
11 | done
12 | echo "$ARGS"
13 | }
14 |
15 | # get the absolute path of the executable
16 | SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- "$0")
17 |
18 | # resolve symlinks
19 | while [ -h "$SELF_PATH" ]; do
20 | DIR=$(dirname -- "$SELF_PATH")
21 | SYM=$(readlink -- "$SELF_PATH")
22 | SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
23 | done
24 |
25 | export PACKAGE_HOME=$(dirname -- "$(dirname -- "$SELF_PATH")")
26 |
27 | source "$PACKAGE_HOME/bin/activate.bash"
28 |
29 | export OLDSEA="$SEA"
30 | export SEA="$PACKAGE_HOME"
31 | export SEALVL="$((SEALVL + 1))"
32 |
33 | if [ "$#" -lt 1 ]; then
34 | echo PATH="$PATH" >&2
35 | echo SEA="$SEA" >&2
36 | echo SEALVL="$SEALVL" >&2
37 | # __SHELL_CUSTOMIZATIONS__
38 | "$SHELL"
39 | else
40 | "$SHELL" -c "$(enquote_all "$@")"
41 | fi
42 | if [ "$OLDSEA" != "" ]; then
43 | echo SEA="$OLDSEA" >&2
44 | fi
45 | echo SEALVL="$((SEALVL - 1))" >&2
46 |
47 |
--------------------------------------------------------------------------------
/bin/sea.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 |
4 | set SHELL=cmd.exe
5 |
6 | set PACKAGE_HOME=%~dp0\..
7 |
8 | call %PACKAGE_HOME%\bin\activate.cmd
9 |
10 | set OLDSEA=%SEA%
11 | set SEA=%PACKAGE_HOME%
12 | set /a SEALVL=%SEALVL% + 1
13 |
14 | if "%1" == "" (
15 | echo SEALVL=%SEALVL%
16 | echo SEA=%SEA%
17 | echo PATH=%PATH%
18 | %SHELL%
19 | ) else (
20 | %SHELL% %*
21 | )
22 |
23 | set /a SEALVL=%SEALVL% - 1
24 | echo SEALVL=%SEALVL%
25 | echo SEA=%OLDSEA%
26 |
--------------------------------------------------------------------------------
/bin/tusk:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 |
3 | if (!require("narwhal/tusk/support").supportsEngine())
4 | require("narwhal").ensureEngine("rhino");
5 |
6 | require('narwhal/tusk').main(system.args);
7 |
--------------------------------------------------------------------------------
/bin/tusk.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 | set HERE=%~dp0
4 | call "%HERE%narwhal.cmd" -m "narwhal/tusk" tusk %*
5 |
6 |
--------------------------------------------------------------------------------
/docs/.gitignore:
--------------------------------------------------------------------------------
1 | *.html
2 |
--------------------------------------------------------------------------------
/docs/download.md:
--------------------------------------------------------------------------------
1 |
2 | Narwhal Downloads
3 | =================
4 |
5 | Download a version of Narwhal then follow the [quick start guide](http://narwhaljs.org/quick-start.html) to get running!
6 |
7 | Bleeding Edge
8 | -------------
9 |
10 | * [Download zip](http://github.com/280north/narwhal/zipball/master)
11 | * [Download tar](http://github.com/280north/narwhal/tarball/master)
12 |
13 | * Git: `git clone git://github.com/280north/narwhal.git`
14 |
15 | * [View tree](http://github.com/280north/narwhal/tree/master)
16 | * [View commit](http://github.com/280north/narwhal/commit/master)
17 |
18 |
19 | Releases
20 | --------
21 |
22 |
Loading...
23 |
24 |
25 |
--------------------------------------------------------------------------------
/docs/engines.md:
--------------------------------------------------------------------------------
1 |
2 | Engines
3 | =======
4 |
5 | Narwhal is a standard library and tools for multiple JavaScript engines; each engine has its own library. Use `tusk engine {name}` to select an engine, or edit `narwhal.conf`. The following engines are presently in development:
6 |
7 | * `rhino`: is the default and most complete engine, based on Mozilla Rhino for Java, used for out-of-the-box functionality.
8 | * `k7`: is a `v8` based engine, in development by Sébastien Pierre.
9 | * `helma`: is based on Rhino with extensions, being developed by Hannes Wallnöefer.
10 | * `xulrunner`: is in development for Firefox extensions and XULRunner applications on the Spidermonkey engine by Irakli Gozalishvili, Christoph Dorn, and Zach Carter.
11 | * `jaxer`: is an engine based on Mozilla SpiderMonkey, for deploying web pages with both server and client side scripts, being developed by Nathan L Smith.
12 | * `v8cgi`: is based on the work of Ondrej Zara, and has not been updated in a long while.
13 | * `default`: is a catchall engine that implements modules that can be shared among engines.
14 | * `browser`: will eventually be available for client side loading of modules with various techniques.
15 | * `secure`: will eventually be available for dependency injection sandboxed module systems within some other engines.
16 |
17 |
18 | Creating new Engine Adapters
19 | ----------------------------
20 |
21 | We have a template for new engines at `engines/template` that you can copy to `engines/{name}` and fill in the blanks. These consist of:
22 |
23 | 1. An executable (shell script or binary) at `engines/{name}/bin/narwhal-{name}` that executes the interpreter engine of choice and causes it to load a bootstrap script. This script will be loaded by `bin/narwhal` with the environment variable `NARWHAL_HOME` set to the Narwhal project directory and `NARWHAL_ENGINE_HOME` set to the engine directory. This script will be run if `NARWHAL_ENGINE` is set to your engine name. You can set `NARWHAL_DEFAULT_ENGINE` or `NARWHAL_ENGINE` in a `narwhal.conf` in your Narwhal project directory (template provided).
24 |
25 | 2. A "thunk", at `engines/{name}/bootstrap.js` that evaluates `narwhal.js` and passes the returned function a preliminary `system` object with a few required properties (`global`, `evalGlobal`, `engine`, `engines`, `print`, `evaluate`, `prefix`, `fs.read`, and `fs.isFile`). This should be enough to get to an interactive console.
26 |
27 | 3. Engine implementations for core modules, such as `file` and `system` located in `engines/{name}/lib/`. You can implement `file-engine` instead of `file` if you implement the subset of the ServerJS file API used by `lib/file.js` (and similar for `io`, `os`, `binary`, etc). The next steps are:
28 |
29 | * system: You must implement `system.args` to be able to pass command line options to Narwhal.
30 |
31 | * file: To enable the package system you must implement `list`, `canonical`, `mtime`, `isDirectory`, `isFile`.
32 |
33 |
--------------------------------------------------------------------------------
/docs/lib/os/popen.md:
--------------------------------------------------------------------------------
1 |
2 | popen(process):Popen
3 |
4 | process may be a String or Array of args. If it is a String, popen uses "/bin/sh", "-e" to execute your program.
5 |
6 | Popen
7 | -----
8 |
9 | Returns an object with the following properties:
10 |
11 | * `stdin IO` - a text writer IO object attached to the stdin of subprocess.
12 | * `stdout IO` - a text reader IO object attached to the stdout of the
13 | supbrocess.
14 | * `stderr IO` - a text reader IO object attached to the stderr of the
15 | subprocess.
16 | * `wait() Number` - blocks on the subprocess until it exits and returns the
17 | exit status code.
18 | * `communicate(stdin_opt, stdout_opt, stderr_opt) Communicate` - communicates
19 | with the process on `stdin`, `stdout`, and `stderr` concurrently with the
20 | attached streams. The given `stdin` may be an IO stream, String, or StringIO
21 | stream. `stdout` and `stderr` may be streams or `StringIO` objects, and
22 | default to `StringIO`. `communicate` returns the streams used to communicate
23 | with `stdin`, `stdout`, and `stderr`, by default providing `stdout` and
24 | `stderr` as `StringIO` objects that have accumulated the entire output and
25 | errput of the subprocess.
26 |
27 | Communicate
28 | -----------
29 |
30 | * `stdin` - the text reader object used to communicate with the subprocess. If
31 | no `stdin` was provided as an argument to `communicate`, `stdin` will be an
32 | empty `StringIO`. If a String was provided, `stdin` will be a `StringIO`
33 | with whatever input was not consumed by the subprocess. If any other stream
34 | was provided, `stdin` will be that stream.
35 | * `stdout` - the text writer object that the subprocess wrote to on `stdout`.
36 | If no `stdout` was provided as an argument to `communicate`, `stdout` will be
37 | a `StringIO` containing all of the accumulated output of the subprocess.
38 | * `stderr` - the text writer object that the subprocess wrote to on stderr. If
39 | no `stderr` was provided as an argument to `communicate`, `stderr` will be a
40 | `StringIO` containing all of the accumulated errput of the subprocess.
41 | * `status` - the exit status code of the subprocess
42 |
43 | Examples
44 | --------
45 |
46 | This is the implementation of "system" in the "os" module:
47 |
48 | OS.system = function (command, options) {
49 | var process = OS.popen(command, options);
50 | return process.communicate(
51 | system.stdin,
52 | system.stdout,
53 | system.stderr
54 | ).status;
55 | };
56 |
57 | This is the implementation of the "command" function in the "os" module. "command" executes a subprocess and returns all of the output of the subprocess as a String. If the exit status code of the subprocess is non-zero, it throws an error containing all of the accumulated errput of the subprocess.
58 |
59 | OS.command = function (command) {
60 | var process = OS.popen(command);
61 | var result = process.communicate();
62 | if (result.status !== 0)
63 | throw new Error(result.stderr.read());
64 | return result.stdout.read();
65 | };
66 |
67 | This function uses the "sort" command to sort a list of numbers.
68 |
69 | var IO = require("io");
70 | var OS = require("os");
71 |
72 | var list = IO.StringIO();
73 | list.print("30");
74 | list.print("4");
75 | list.print("1000");
76 | list.print("200");
77 |
78 | var process = OS.popen(["sort", "-n", "-"]);
79 | process.communicate(list).stdout.forEach(print);
80 |
81 |
--------------------------------------------------------------------------------
/docs/lib/system.md:
--------------------------------------------------------------------------------
1 |
2 | CommonJS Standard:
3 |
4 | * `args`
5 | * `env`
6 | * `stdin`
7 | * `stdout`
8 | * `stderr`
9 |
10 | Bootstrap protocol:
11 |
12 | * `prefixes`
13 | * `prefix`
14 | * `enginePrefix`
15 | * `global`
16 | * `engine`
17 | * `engines`
18 | * `os` =~ /\bwin(dows|nt)\b/i
19 | * `print`
20 | * `evaluate`
21 | * `debug`
22 | * `verbose`
23 | * `evalGlobal`
24 |
25 | Rhino:
26 |
27 | * `originalArgs`
28 | * `appEngine`
29 | * `appEngineHosting`
30 | * `log` Deprecated?
31 | * `fs` Deprecated?
32 |
33 |
--------------------------------------------------------------------------------
/docs/modules-advanced.md:
--------------------------------------------------------------------------------
1 |
2 | When you require a module the first time, Narwhal constructs a function from
3 | the text of the module and executes it with three named arguments:
4 |
5 | * `require`
6 | * `exports`
7 | * `module`
8 |
9 | Narwhal memoizes the exports object before it calls the "module factory
10 | function" so it gets returned immediately if your module gets required by one
11 | of its deep dependencies. The exports object is what `require` returns. It
12 | also guarantees that, in a single system of modules, the module factory
13 | function only gets called once. However, Narwhal also exposes all of the
14 | machinery it uses to load and execute modules so you can:
15 |
16 | - create a new system of modules, a "sandbox",
17 | - create new module loaders,
18 | - share a module loader with any number of sandboxes to cut down on time wasted
19 | parsing modules repeatedly,
20 | - execute a module factory function with any named arguments at any time,
21 | - execute a module factory function with a one-time-use `exports` object, `require`
22 | function and, `module` object with any additional free variables.
23 |
24 | Making a module subsystem is great for test scaffolding and eventually will be
25 | useful for partitioning secure subsystems and injecting dependencies into that
26 | system. Narwhal's module system's own testing scaffold uses this feature.
27 |
28 | Calling a module with additional free variables is great for constructing
29 | domain specific languages. `Jakefile`, `QUnit`, or `Bogart` would be great
30 | use-cases for this feature.
31 |
32 | To get a module factory function, call `require.load(id)`. The module factory
33 | function takes one argument: an object that owns the named free variables to
34 | inject into the module's lexical scope.
35 |
36 | `foo.js`:
37 |
38 | return a + b;
39 |
40 | `bar.js`:
41 |
42 | require.load("foo")({a: 10, b: 20}) === 30
43 |
44 | When you use "load", the module gets exactly the free variables you have
45 | given it. If you want `require`, `exports`, and `module` to exist in that
46 | scope, you must either inject them manually (which is somewhat involved),
47 | or you can use the `require.once(id, scope)` convenience function.
48 |
49 | `qux.js`:
50 |
51 | var ASSERT = require("assert");
52 | ASSERT.equal(a + b, 30);
53 |
54 | `quux.js`:
55 |
56 | require.once("qux", {a: 20, b: 10});
57 |
58 | Future topics:
59 |
60 | * `require("sandbox")`
61 | * `require("loader")`
62 | * `load`
63 | * `require.loader`
64 | * `require.loader.resolve(id, baseId)`
65 | * `require.loader.find`
66 | * `require.paths`
67 | * `require.loader.loaders`
68 |
69 |
--------------------------------------------------------------------------------
/docs/modules.md:
--------------------------------------------------------------------------------
1 |
2 | Narwhal Modules
3 | ===============
4 |
5 | Narwhal "scripts" are [CommonJS](http://wiki.commonjs.org/wiki/Modules/1.1) compatible modules, much like Python or Ruby modules. You do not have to use module pattern boilerplate; every module has its own local scope. You can get the exports object of another module by calling `require`.
6 |
7 | var FS = require("file");
8 | FS.isFile("foo.txt");
9 |
10 | Module identifiers for `require` come in three flavors: "top-level", "relative", and "absolute". In the above case, "file" is a "top-level" identifier, so it will load any module called "file.js" in the "lib" directory of whichever package comes first in the load path. Relative identifiers have "." or ".." as their first term, and terms are delimited with "/". So, in the "foo/bar" module, "require('./baz')" will load "foo/baz". Absolute module identifiers should not be used directly, but are produced when you execute a program module outside the module path. The module is identified by its fully-qualified path, starting with "/".
11 |
12 | You can export an object by assigning it to `exports`.
13 |
14 | exports.foo = function () {
15 | return "Hello";
16 | };
17 |
18 | In a module, you also get a `module` object that has `module.id` and `module.path` properties so you can inspect your own top-level module identifier, and the path of your own module file. You also get a `require.main` property that tells you the top-level module identifier of the module that started the program.
19 |
20 | if (require.main == module)
21 | main();
22 |
23 | var settings = require(require.main);
24 |
25 | var FS = require("file");
26 | var path = FS.path(module.path);
27 | var indexHtml = path.resolve("./template/index.html").read();
28 |
29 | Beyond the CommonJS specification, you also get the `print` function and the `system` module object for free. The `print` function accepts variadic arguments and writes a single line containing the arguments delimited by spaces to standard output and flushes. The `system` module can be explicitly required with `require("system")` as is encouraged since it is necessary for CommonJS compliance. Do not use `print` or `system` in standard libraries.
30 |
31 |
32 | A Brief Tour
33 | ============
34 |
35 | The main modules of the standard library are "system", "file", "io", and "os". There are also handy "json", "args", and "util" modules for a JSON codec, command line argument parsers, and utility functions.
36 |
37 | I have already introduced `system`. The "file" module implements functions like "open", "read", "write", "copy", "move", "list", and others. "os" exports commands like "system", "command", "exit", "popen", and "enquote" for shell args.
38 |
39 |
--------------------------------------------------------------------------------
/docs/packages-howto.md:
--------------------------------------------------------------------------------
1 |
2 | How to make Packages
3 | ====================
4 |
5 | A package consists of a directory of modules conforming to the ServerJS [Securable Modules](https://wiki.mozilla.org/ServerJS/Modules/SecurableModules) specification, and a "package.json" file in the root of the package containing the location of the modules, depedencies, and other metadata.
6 |
7 | A package directory might have the following files and directories:
8 |
9 | * `package.json` for package metadata like dependencies and overrides for the conventional directory names.
10 | * `local.json` for overrides on `package.json` provided by the user.
11 | * `bin` for executables.
12 | * `lib` for all object code, including JavaScript modules, and C extensions.
13 | * `src` for all buildable source code, including C and Java source code.
14 | * `jars` for Java class trees and archives.
15 | * `packages/{name}` for installed sub-packages.
16 | * `engines/{engine}` for engine-specific packages.
17 |
18 | `package.json` and `local.json` may contain the following attributes:
19 |
20 | * `name` - the name of the package. The package system will only load one package with a given name. The name defaults to the name of the parent directory.
21 | * `author` - the original author of the package. The author may be a String including an optional `(` URL in parentheses `)` and optional `<` email address in angle brackets `>`. Alternately, it may be an Object with any of `name`, `email`, and `url` attributes. The package reader normalizes authors to the latter Object form.
22 | * `maintainer` - the package maintainer for the project as a String or Object just as the author attribute.
23 | * `contributors` - may be an Array of additional author Strings.
24 | * `url` - the URL of the project website.
25 | * `license` - the name of the license as a String, with an optional URL in parentheses, or an Object with `name` and `url` attributes.
26 | * `description` - a String describing the package. Most package descriptions end with a period/full stop.
27 | * `keywords` - an Array of String keywords to assist users searching for the package with `tusk search` or `tusk apropos`.
28 | * `lib` - a path or array of paths to top-level module directories provided in this package. Defaults to `["lib"]`.
29 | * `jars` - for Rhino engines, a path or array of paths to directories to add to the Java CLASSPATH (uses a Java URLClassLoader, so accepts `.jar` paths and directory paths ending with `/`).
30 | * `packages` - a path or array of paths to directories containing additional packages, defaults to `["packages"]`.
31 | * `engines` - a path or array of paths to directories containing engine-specific packages, defaults to `["engines"]`. These engine packages will be loaded if and in the prioritized order they appear in the `system.engines` array, and with higher priority that those in this package's generic `js` path so that they can override engine-specific modules.
32 |
33 | For more information on how packages are composed into catalogs, see the [catalog](catalog.html) reference.
34 |
--------------------------------------------------------------------------------
/docs/posts/2009-07-29-hello-0.1.md:
--------------------------------------------------------------------------------
1 | Hello 0.1
2 | =========
3 |
4 | Today we're announcing [Narwhal](http://narwhaljs.org/) 0.1 and [Jack](http://jackjs.org/) 0.1.
5 |
6 | ### Download
7 |
8 | * Narwhal 0.1: [tar](http://github.com/280north/narwhal/tarball/v0.1), [zip](http://github.com/280north/narwhal/zipball/v0.1)
9 | * Jack 0.1: [tar](http://github.com/280north/jack/tarball/v0.1), [zip](http://github.com/280north/jack/zipball/v0.1)
10 |
11 | Check out the [quick start guide](http://narwhaljs.org/quick-start.html) for instructions on getting up and running with Narwhal and Jack.
12 |
13 | ### Release Notes
14 |
15 | * Complete [securable modules](https://wiki.mozilla.org/ServerJS/Modules/SecurableModules) implementation, in JavaScript, with hooks for native module loading.
16 | * Various modules, including `file`, `binary`, `os`, `system`, `args`, and many others.
17 | * The "tusk" package manager, currently using [Github](http://github.com/) as a package repository.
18 | * Full support for the Rhino interpreter, and partial support for numerous other [engines](http://narwhaljs.org/engines.html).
19 | * Full support for Mac OS X, Linux, and other Unixes. Preliminary support for Windows.
20 |
--------------------------------------------------------------------------------
/docs/quick-start.md:
--------------------------------------------------------------------------------
1 |
2 | Narwhal Quick Start
3 | ===================
4 |
5 | Download Narwhal.
6 |
7 | * download and extract the [zip](http://github.com/280north/narwhal/zipball/master) or [tar](http://github.com/280north/narwhal/tarball/master) archive, or
8 | * `git clone git://github.com/280north/narwhal.git`
9 |
10 | Put Narwhal on your PATH environment variable.
11 |
12 | * `export PATH=$PATH:~/narwhal/bin`, or
13 | * `source narwhal/bin/activate`
14 |
15 | Run `narwhal` or `js` (they are equivalent).
16 |
17 | * `js narwhal/examples/hello`
18 |
19 | Look at the options for Narwhal.
20 |
21 | * `js --help`
22 |
23 | And for Tusk, the package manager and virtual environment tool.
24 |
25 | * `tusk help`
26 |
27 |
28 | My First Web Server
29 | ===================
30 |
31 | Create a project "hello-web".
32 |
33 | tusk init hello-web
34 | cd hello-web
35 |
36 | Enter your project as a "virtual environment" using `activate` or `sea` so that its libraries, binaries, and packages get automatically installed when you run Narwhal.
37 |
38 | source bin/activate
39 |
40 | or
41 |
42 | bin/sea
43 |
44 | Install some packages you will need, like Jack, the JSGI standard library for interoperable web services.
45 |
46 | tusk install jack
47 |
48 | Tusk gets downloaded and installed at "hello-web/packages/jack".
49 |
50 | Create your "jackconfig.js". This is a trivial JSGI compatible application, wrapped in the `ContentLength` middleware to automatically set the "Content-Length" header.
51 |
52 | exports.app = function(env) {
53 | var text = "Hello, Web!";
54 | return {
55 | status : 200,
56 | headers : { "Content-Type" : "text/plain", "Content-Length" : String(text.length) },
57 | body : [text]
58 | };
59 | };
60 |
61 | Run it!
62 |
63 | jackup
64 |
65 | `jackup` looks for a file called `jackconfig.js` in the current directory, or you can specify a path to a Jack application.
66 |
67 | Open [http://localhost:8080/](http://localhost:8080/) in your web browser.
68 |
69 | Next, take a look at the introduction to [modules](modules.html), for a primer on using and making modules in Narwhal.
70 |
--------------------------------------------------------------------------------
/docs/sea.md:
--------------------------------------------------------------------------------
1 |
2 | Narwhal, Tusk, and Sea
3 | ======================
4 |
5 | Narwhal is your JavaScript interpreter. It is executable with `narwhal` or `js`. See `narwhal --help` for a list of its options. It is comparable to your shell, Python or Ruby/IRB.
6 |
7 | Tusk is your package manager. Tusk by default installs packages whereever `narwhal` is installed. See `tusk help` for a list of options. It is comparable to `apt` or `gem`. You can also use `tusk` to create new "packages", application project scaffolds, or "virtual environments", which are all share a common structure.
8 |
9 | `sea` is a tool for entering a Narwhal "virtual environment". It executes a command or reexecutes your shell inside a "virtual environment". There is a version of `sea` that comes packed with "Narwhal", that you can use to "enter" your system `narwhal` environment, which is handy if `narwhal/bin` is not on your path. You can also `source bin/activate`, as long as your version of bash supports the `${BASH_ARGV[0]}` notation, or if your current working directory contains `bin/activate`.
10 |
11 | You can use `narwhal`, `tusk`, and `sea` to create multiple, independent, reproducable Narwhal project installations. Assuming that `narwhal` and `tusk` are on your path, you can use `tusk init` to create two application projects.
12 |
13 | $ tusk init foo
14 | $ tusk init bar
15 | $ cd foo
16 | foo$ bin/sea
17 | PATH=foo/bin
18 | SEALVL=1
19 | foo$ tusk install jack
20 | foo$ edit jackconfig.js
21 | foo$ jackup
22 | Loading configuration module at foo/jackconfig
23 | Jack is starting up using Simple on port 8080
24 | ^C
25 | foo$ echo $SEA
26 | foo
27 | foo$ which sea
28 | foo/bin/sea
29 | foo$ exit
30 | SEALVL=0
31 | foo$ cd ../bar
32 | bar$ bin/sea
33 | PATH=bar/bin
34 | SEALVL=1
35 | ...
36 |
37 | When you are in a Sea, Narwhal loads all of the packages installed in that Sea and Tusk installs packages in your Sea. While you can manipulate the NARWHAL_PATH and JS_PATH environment variables manually, Seas obviate the need.
38 |
39 | Each sea can also have a different JavaScript engine. Edit `narwhal.conf` in your Sea to use a different engine.
40 |
41 | $ js -e 'print(system.engine)'
42 | rhino
43 | $ cat bar/narwhal.conf
44 | NARWHAL_DEFAULT_PLATFORM=v8
45 | $ bar/bin/sea 'js -e "print(system.engine)"'
46 | v8
47 | PATH=/bin
48 | SEALVL=0
49 |
50 |
--------------------------------------------------------------------------------
/docs/test.md:
--------------------------------------------------------------------------------
1 |
2 | Testing
3 | =======
4 |
5 | Narwhal supports the [CommonJS Unit Test API
6 | 1.0](http://wiki.commonjs.org/wiki/Unit_Testing/1.0). You can run any unit
7 | test script with the `"js -m test"` command.
8 |
9 | js -m test tests/all-tests.js
10 |
11 | Some tests include a snippet on the bottom that allows them to self-run, in
12 | which case it is sufficient to run the script directly.
13 |
14 | js tests/all-tests.js
15 |
16 | The boilerplate looks like this:
17 |
18 | if (require.main == module)
19 | require("os").exit(require("test").run(exports));
20 |
21 | You can construct your own unit tests by creating a JavaScript module that
22 | exports `test*` functions, and uses the `assert` module to throw an
23 | `AssertionError` if a test fails.
24 |
25 | exports.testFoo = function () {
26 | assert.ok(true);
27 | assert.equals(2 + 2, 5, "three sir!");
28 | };
29 |
30 | Alternately, if you prefer a test to continue running all test points even
31 | after one of the assertions fails, you can use the logging assertion mechansim,
32 | which is an `assert` object with the same API as the assert module that
33 | gets quietly passed to your test functions. It is a different logger object
34 | for each module.
35 |
36 | exports['test my feature'] = function (assert) {
37 | assert.ok(false);
38 | assert.ok(true);
39 | };
40 |
41 | Customization
42 | -------------
43 |
44 | The CommonJS Unit Testing specification codifies a very small subset of the
45 | components you need for a unit testing framework, so that multiple frameworks
46 | can run interoperably. Two of the other pluggable parts are the test logging
47 | system and custom syntactic sugar for advanced assertions.
48 |
49 | ### Logging
50 |
51 | To have the test runner direct logs to an alternate system, pass an alternate
52 | logger object to the `test` module's `run` method.
53 |
54 | require("test").run(exports, new Log());
55 |
56 | The logger object needs to conform to the logger API set out in the `test`
57 | module. That involves providing implementations of the following function
58 | properties:
59 |
60 | * `pass(message_opt)`
61 | * `fail(assertion)`
62 | * `error(exception)`
63 | * `section(name:String):Log`
64 |
65 | The assertion object has the following properties:
66 |
67 | * `name` `AssertionError`
68 | * `message`
69 | * `actual`
70 | * `expected`
71 | * `operator`
72 |
73 | ### Assertions
74 |
75 | You can create complex assertions by providing functions that can throw
76 | `AssertionError`. One fashionable technique is to provide a chaining API.
77 |
78 | expect(x).is(y);
79 |
80 | To enable this simple case:
81 |
82 | var assert = require("assert");
83 |
84 | var expect = function (actual) {
85 | var self = {};
86 | self.is = function (expected, message) {
87 | if (!is(expected, actual)) {
88 | throw new assert.AssertionError({
89 | "expected": expected,
90 | "actual": actual,
91 | "message": message,
92 | "operator": "is"
93 | });
94 | }
95 | };
96 | return self;
97 | };
98 |
99 | // from Caja
100 | function is(x, y) {
101 | if (x === y) {
102 | return x !== 0 || 1/x === 1/y;
103 | } else {
104 | return x !== x && y !== y;
105 | }
106 | }
107 |
108 |
--------------------------------------------------------------------------------
/engines/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore all
2 |
3 | /*
4 |
5 | # except for
6 |
7 | !/.gitignore
8 |
9 | !/browser
10 | !/default
11 | !/rhino
12 | !/secure
13 | !/template
14 |
--------------------------------------------------------------------------------
/engines/browser/lib/binary.js:
--------------------------------------------------------------------------------
1 | // -- tlrobinson Tom Robinson
2 | // -- cadorn Christoph Dorn
3 | exports.ByteString = String;
4 | exports.ByteArray = Array;
5 |
--------------------------------------------------------------------------------
/engines/browser/lib/reactor.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- cadorn Christoph Dorn
4 |
5 | var active = false;
6 | var pending = [];
7 | var run = function () {
8 | var task = pending.shift();
9 | if (0 === pending.length) {
10 | active = false;
11 | } else {
12 | setTimeout(run, 0);
13 | }
14 | task();
15 | };
16 |
17 | exports.enqueue = function enqueue(task) {
18 | pending.push(task);
19 | if (!active) {
20 | setTimeout(run, 0);
21 | active = true;
22 | }
23 | };
24 |
25 |
--------------------------------------------------------------------------------
/engines/browser/lib/system.js:
--------------------------------------------------------------------------------
1 |
2 | // -- cadorn Christoph Dorn
3 |
4 | exports.print = function () {
5 | system.print.apply(system, arguments);
6 | };
7 |
--------------------------------------------------------------------------------
/engines/default/lib/binary-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | exports.B_LENGTH = function(bytes) {
5 | return bytes.length;
6 | }
7 |
8 | exports.B_ALLOC = function(length) {
9 | var bytes = new Array(length);
10 | for (var i = 0; i < length; i++)
11 | bytes[i] = 0;
12 | return bytes;
13 | }
14 |
15 | exports.B_FILL = function(bytes, from, to, value) {
16 | for (var i = from; i < to; i++)
17 | bytes[i] = value;
18 | }
19 |
20 | exports.B_COPY = function(src, srcOffset, dst, dstOffset, length) {
21 | for (var i = 0; i < length; i++)
22 | dst[dstOffset+i] = src[srcOffset+i];
23 | }
24 |
25 | exports.B_GET = function(bytes, index) {
26 | return bytes[index];
27 | }
28 |
29 | exports.B_SET = function(bytes, index, value) {
30 | return bytes[index] = value;
31 | }
32 |
33 | var DEFAULT_ENCODING = "UTF-8";
34 |
35 | exports.B_DECODE = function(bytes, offset, length, codec) {
36 | var newBytes = exports.B_TRANSCODE(bytes, offset, length, codec, DEFAULT_ENCODING);
37 | return exports.B_DECODE_DEFAULT(newBytes, 0, exports.B_LENGTH(newBytes));
38 | }
39 |
40 | exports.B_DECODE_DEFAULT = function(bytes, offset, length) {
41 | throw "NYI";
42 | }
43 |
44 | exports.B_ENCODE = function(string, codec) {
45 | var bytes = exports.B_ENCODE_DEFAULT(string);
46 | return exports.B_TRANSCODE(bytes, 0, exports.B_LENGTH(bytes), DEFAULT_ENCODING, codec);
47 | }
48 |
49 | exports.B_ENCODE_DEFAULT = function(string) {
50 | throw "NYI";
51 | }
52 |
53 | exports.B_TRANSCODE = function(bytes, offset, length, sourceCodec, targetCodec) {
54 | throw "NYI";
55 | }
56 |
57 |
--------------------------------------------------------------------------------
/engines/default/lib/file-engine.js:
--------------------------------------------------------------------------------
1 | throw new Error(
2 | "This module is no longer supported. Please contact the\n" +
3 | "Narwhal developer team if you see this exception.");
4 |
--------------------------------------------------------------------------------
/engines/default/lib/global-commonjs.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | require("global-es5");
5 |
6 | // https://wiki.mozilla.org/ServerJS/Binary/B
7 | if (!String.prototype.toByteString)
8 | Object.defineProperty(String.prototype, "toByteString", {
9 | "value": function(charset) {
10 | // RHINO bug: it thinks "this" is a Java string (?!)
11 | var binary = require("binary");
12 | return new binary.ByteString(String(this), charset);
13 | },
14 | "enumerable": false
15 | });
16 |
17 | // https://wiki.mozilla.org/ServerJS/Binary/B
18 | if (!String.prototype.toByteArray)
19 | Object.defineProperty(String.prototype, 'toByteArray', {
20 | "value": function(charset) {
21 | // RHINO bug: it thinks "this" is a Java string (?!)
22 | var binary = require("binary");
23 | return new binary.ByteArray(String(this), charset);
24 | },
25 | "enumerable": false
26 | });
27 |
28 | // https://wiki.mozilla.org/ServerJS/Binary/B
29 | if (!String.prototype.charCodes)
30 | Object.defineProperty(String.prototype, 'charCodes', {
31 | "value": function () {
32 | return Array.prototype.map.call(this, function (c) {
33 | return c.charCodeAt();
34 | });
35 | },
36 | "enumerable": false
37 | });
38 |
39 | // https://wiki.mozilla.org/ServerJS/Binary/B
40 | if (!String.fromCharCodes)
41 | Object.defineProperty(String, 'fromCharCodes', {
42 | "value": function (codes) {
43 | return codes.map(String.fromCharCode).join('');
44 | },
45 | "enumerable": false
46 | });
47 |
48 | // https://wiki.mozilla.org/ServerJS/Binary/B
49 | if (!Array.prototype.toByteString)
50 | Object.defineProperty(Array.prototype, 'toByteString', {
51 | "value": function(charset) {
52 | return new require("binary").ByteString(this);
53 | },
54 | "enumerable": false
55 | });
56 |
57 | if (!Array.prototype.toByteArray)
58 | Object.defineProperty(Array.prototype, 'toByteArray', {
59 | "value": function(charset) {
60 | return new ByteArray(this);
61 | },
62 | "enumerable": false
63 | });
64 |
65 |
--------------------------------------------------------------------------------
/engines/default/lib/global.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | require("./global-es5");
5 | require("./global-commonjs");
6 |
7 | // RegExp
8 | // ======
9 |
10 | /*** RegExp.escape
11 | accepts a string; returns the string with regex metacharacters escaped.
12 | the returned string can safely be used within a regex to match a literal
13 | string. escaped characters are [, ], {, }, (, ), -, *, +, ?, ., \, ^, $,
14 | |, #, [comma], and whitespace.
15 | */
16 | RegExp.escape = function (str) {
17 | return str.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, "\\$&");
18 | };
19 |
20 |
--------------------------------------------------------------------------------
/engines/default/lib/io-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // IO: default
3 | // -- tlrobinson Tom Robinson
4 |
5 | var IO = exports.IO = function(inputStream, outputStream) {
6 | this.inputStream = inputStream;
7 | this.outputStream = outputStream;
8 | }
9 |
10 | IO.prototype.read = function(length) {
11 | return this.inputStream(length);
12 | }
13 |
14 | IO.prototype.write = function(object) {
15 | this.outputStream(object);
16 | return this;
17 | }
18 |
19 | IO.prototype.flush = function() {
20 | return this;
21 | }
22 |
23 | IO.prototype.close = function() {
24 | }
25 |
26 | exports.TextIOWrapper = function (raw, mode, lineBuffering, buffering, charset, options) {
27 | return raw;
28 | }
29 |
--------------------------------------------------------------------------------
/engines/default/lib/os-engine.js:
--------------------------------------------------------------------------------
1 | // -- cadorn Christoph Dorn
2 | exports.exit = function(status) {
3 | throw new Error("Exiting with status="+status);
4 | }
5 |
--------------------------------------------------------------------------------
/engines/default/lib/reactor.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tasks = [];
5 |
6 | require('unload').when(function () {
7 | while (tasks.length)
8 | tasks.shift()();
9 | });
10 |
11 | exports.enqueue = function (task) {
12 | tasks.push(task);
13 | };
14 |
15 |
--------------------------------------------------------------------------------
/engines/default/lib/system.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
4 |
5 | var IO = require("./io").IO;
6 |
7 | exports.print = function () {
8 | exports.stdout.write(Array.prototype.join.call(arguments, ' ') + "\n").flush();
9 | };
10 |
11 | exports.stdin = new IO(function () {}, null);
12 | exports.stdout = new IO(null, function(string) {
13 | exports.print(String(string).replace(/\n$/,""));
14 | });
15 | exports.stderr = new IO(null, function(string) {
16 | exports.print(String(string).replace(/\n$/,""));
17 | });
18 |
19 | exports.args = global.arguments || [];
20 |
21 | exports.env = {};
22 |
23 | exports.fs = require('./file');
24 |
25 | // default logger
26 | var Logger = require("logger").Logger;
27 | exports.log = new Logger(exports.stderr);
28 |
29 |
--------------------------------------------------------------------------------
/engines/rhino/bin/narwhal-rhino:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # get the absolute path of the executable
4 | SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH="$SELF_PATH/$(basename -- "$0")"
5 |
6 | # resolve symlinks
7 | while [ -h "$SELF_PATH" ]; do
8 | DIR=$(dirname -- "$SELF_PATH")
9 | SYM=$(readlink -- "$SELF_PATH")
10 | SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
11 | done
12 |
13 | # NARWHAL_ENGINE_HOME is the 2nd ancestor directory of this shell script
14 | export NARWHAL_ENGINE_HOME=$(dirname -- "$(dirname -- "$SELF_PATH")")
15 |
16 | BOOTSTRAP=$NARWHAL_ENGINE_HOME/bootstrap.js
17 |
18 | if [ -z "$NARWHAL_HOME" ]; then
19 | export NARWHAL_HOME=$(dirname -- "$(dirname -- "$NARWHAL_ENGINE_HOME")")
20 | fi
21 |
22 | CLASSPATH=$NARWHAL_ENGINE_HOME/jars/jna.jar
23 | BOOTCLASSPATH=$NARWHAL_ENGINE_HOME/jars/js.jar
24 | JAVA_OPTS=""
25 | isOpenJDK=`java -version 2>&1 | grep -i "OpenJDK" | wc -l`
26 |
27 | if [ -n "$NARWHAL_CLASSPATH" ]; then
28 | CLASSPATH=$NARWHAL_CLASSPATH:$CLASSPATH
29 | fi
30 |
31 | if [ "$(which cygpath 2>/dev/null)" ]; then
32 | CLASSPATH=$(cygpath -wp -- "$CLASSPATH")
33 | BOOTCLASSPATH=$(cygpath -wp -- "$BOOTCLASSPATH")
34 | BOOTSTRAP=$(cygpath -wa -- "$BOOTSTRAP")
35 | export NARWHAL_HOME=$(cygpath -wa -- "$NARWHAL_HOME")
36 | export NARWHAL_ENGINE_HOME=$(cygpath -wa -- "$NARWHAL_ENGINE_HOME")
37 | fi
38 |
39 | if [ -z "$NARWHAL_JS_VERSION" ]; then
40 | NARWHAL_JS_VERSION=170
41 | fi
42 |
43 | if [ -z "$NARWHAL_DEBUGGER" ] || [ "$NARWHAL_DEBUGGER" -eq 0 ]; then
44 | JAVA_MAIN=org.mozilla.javascript.tools.shell.Main
45 | else
46 | JAVA_MAIN=org.mozilla.javascript.tools.debugger.Main
47 | fi
48 |
49 | # check the java version number in the most complicated fashion imaginable
50 | JAVA_VERSION=$(java -version 2>&1 | awk -F '[ ".]+' 'NR==1 {print $3 "." $4}')
51 | LOWER_VERSION=$( (echo "$JAVA_VERSION"; echo "1.5") | sort -n | head -n 1)
52 | if [ "$LOWER_VERSION" != "1.5" ]; then
53 | echo "Narwhal on Rhino requires Java 1.5 or higher. You have $JAVA_VERSION."
54 | exit
55 | fi
56 |
57 | # drop into shell if there are no additional arguments
58 | if [ $# -lt 1 ]; then
59 | # prefer rlwrap to jline.
60 | RLWRAP="$(which rlwrap)"
61 | if [ -x "$RLWRAP" ]; then
62 | RLWRAP="$RLWRAP -C narwhal"
63 | else
64 | RLWRAP=""
65 | CLASSPATH="$CLASSPATH:$NARWHAL_ENGINE_HOME/jars/jline.jar"
66 | fi
67 | $RLWRAP java $JAVA_OPTS $NARWHAL_JAVA_ARGUMENTS -cp "$BOOTCLASSPATH:$CLASSPATH" "$JAVA_MAIN" -f "$BOOTSTRAP" -f -
68 | else
69 | java $JAVA_OPTS $NARWHAL_JAVA_ARGUMENTS -cp "$BOOTCLASSPATH:$CLASSPATH" "$JAVA_MAIN" -version "$NARWHAL_JS_VERSION" "$BOOTSTRAP" "$0" "$@"
70 | fi
71 |
72 |
--------------------------------------------------------------------------------
/engines/rhino/bin/narwhal-rhino.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 |
4 | :: NARWHAL_ENGINE_HOME is the parent the bin directory
5 | set NARWHAL_ENGINE_HOME=%~dp0..
6 |
7 | set BOOTSTRAP=%NARWHAL_ENGINE_HOME%\bootstrap.js
8 |
9 | if "%NARWHAL_HOME%" == "" (
10 | set NARWHAL_HOME=%NARWHAL_ENGINE_HOME%\..\..
11 | )
12 |
13 | setlocal ENABLEDELAYEDEXPANSION
14 | set CLASSPATH=
15 | for /R "%NARWHAL_ENGINE_HOME%\jars" %%g in (*.jar) do set CLASSPATH=!CLASSPATH!;%%g
16 |
17 | if not "%NARWHAL_CLASSPATH%" == "" (
18 | set CLASSPATH=%NARWHAL_CLASSPATH%;%CLASSPATH%
19 | )
20 |
21 | if "%NARWHAL_DEBUGGER%" == "" (
22 | set JAVA_MAIN=org.mozilla.javascript.tools.shell.Main
23 | ) else (
24 | set JAVA_MAIN=org.mozilla.javascript.tools.debugger.Main
25 | )
26 |
27 |
28 | :: drop into shell if there are no additional arguments
29 | if "%1" == "" (
30 | java -cp "%CLASSPATH%" "%JAVA_MAIN%" -f "%BOOTSTRAP%" -f -
31 | ) else (
32 | java -cp "%CLASSPATH%" "%JAVA_MAIN%" "%BOOTSTRAP%" %0 %*
33 | )
34 |
--------------------------------------------------------------------------------
/engines/rhino/jars/jline.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/engines/rhino/jars/jline.jar
--------------------------------------------------------------------------------
/engines/rhino/jars/jna.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/engines/rhino/jars/jna.jar
--------------------------------------------------------------------------------
/engines/rhino/jars/js.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/engines/rhino/jars/js.jar
--------------------------------------------------------------------------------
/engines/rhino/lib/binary-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | exports.B_LENGTH = function(bytes) {
5 | return bytes.length;
6 | }
7 |
8 | exports.B_ALLOC = function(length) {
9 | return Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, length);
10 | }
11 |
12 | exports.B_FILL = function(bytes, length, offset, value) {
13 | Packages.java.util.Arrays.fill(bytes, length, offset, value);
14 | }
15 |
16 | exports.B_COPY = function(src, srcOffset, dst, dstOffset, length) {
17 | Packages.java.lang.System.arraycopy(src, srcOffset, dst, dstOffset, length);
18 | }
19 |
20 | exports.B_GET = function(bytes, index) {
21 | return (bytes[index] >>> 0) & 0xFF;
22 | }
23 |
24 | exports.B_SET = function(bytes, index, value) {
25 | return bytes[index] = ((value & 0x80) ? -1 - (value ^ 0xFF) : value);
26 | }
27 |
28 | exports.B_DECODE = function(bytes, offset, length, codec) {
29 | return String(new Packages.java.lang.String(bytes, offset, length, codec));
30 | }
31 | /*
32 | exports.B_DECODE_DEFAULT = function(bytes, offset, length) {
33 | return String(new Packages.java.lang.String(bytes, offset, length));
34 | }
35 | */
36 | exports.B_DECODE_DEFAULT = function(bytes, offset, length) {
37 | return String(new Packages.java.lang.String(bytes, offset, length, "UTF-8"));
38 | }
39 |
40 | exports.B_ENCODE = function(string, codec) {
41 | return new Packages.java.lang.String(string).getBytes(codec);
42 | }
43 | /*
44 | exports.B_ENCODE_DEFAULT = function(string) {
45 | return new Packages.java.lang.String(string).getBytes();
46 | }
47 | */
48 | exports.B_ENCODE_DEFAULT = function(string) {
49 | return new Packages.java.lang.String(string).getBytes("UTF-8");
50 | }
51 |
52 | exports.B_TRANSCODE = function(bytes, offset, length, sourceCodec, targetCodec) {
53 | return new Packages.java.lang.String(bytes, offset, length, sourceCodec).getBytes(targetCodec);
54 | }
55 |
56 | function wrapper(that) {
57 | var obj = new JavaAdapter(
58 | Packages.org.mozilla.javascript.ScriptableObject,
59 | Packages.org.mozilla.javascript.Wrapper,
60 | {
61 | get : function(index, start) {
62 | if (typeof index === "number")
63 | return that.get(index);
64 |
65 | return that[index];
66 | },
67 | has : function(index, start) {
68 | if (typeof index === "number")
69 | return index < that._length;
70 |
71 | return (that[index] !== undefined)
72 | },
73 | put : function(index, start, value) {
74 | if (typeof index === "number")
75 | that.set(index, value);
76 | else
77 | that[index] = value;
78 | },
79 | unwrap : function() {
80 | var bytes = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, that._length);
81 | Packages.java.lang.System.arraycopy(that._bytes, that._offset, bytes, 0, that._length);
82 | return bytes;
83 | }
84 | }
85 | );
86 |
87 | obj.__proto__ = that;
88 |
89 | return obj;
90 | }
91 |
92 | // FIXME: disabling these because it broke several tests. figure out why.
93 | //exports.ByteStringWrapper = wrapper;
94 | //exports.ByteArrayWrapper = wrapper;
95 |
--------------------------------------------------------------------------------
/engines/rhino/lib/concurrency.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Provides some currency help
3 | */
4 | exports.Lock = java.util.concurrent.locks.ReentrantReadWriteLock;
5 | exports.sync = sync; // already there in Rhino
6 | exports.ThreadLocal = java.lang.ThreadLocal;
7 |
--------------------------------------------------------------------------------
/engines/rhino/lib/event-queue.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriszyp Kris Zyp
3 |
4 | /**
5 | * Represents the event queue for a vat
6 | * The API is modeled after https://developer.mozilla.org/en/nsIThread
7 | */
8 |
9 | // we could eventually upgrade to PriorityBlockingQueye with FIFOEntry tie breaking
10 | var loopLevel = 0,
11 | shuttingDown,
12 | queue = new java.util.concurrent.LinkedBlockingQueue();
13 |
14 |
15 | exports.getNextEvent = function(){
16 | return queue.take();
17 | };
18 |
19 | exports.processNextEvent = function(mayWait){
20 | if(!mayWait && queue.isEmpty()){
21 | return false;
22 | }
23 | try{
24 | var next = queue.take();
25 | next();
26 | }catch(e){
27 | exports.enqueue(function(){
28 | if(typeof onerror === "function"){
29 | // trigger the onerror event in the worker if an error occurs
30 | try{
31 | onerror(e);
32 | }
33 | catch(e){
34 | // don't want an error here to go into an infinite loop!
35 | exports.defaultErrorReporter(e);
36 | }
37 | }
38 | else{
39 | exports.defaultErrorReporter(e);
40 | }
41 | });
42 |
43 |
44 | }
45 | return true;
46 | };
47 |
48 | exports.enterEventLoop = function(onidle){
49 | shuttingDown = false;
50 | loopLevel++;
51 | var currentLoopLevel = loopLevel;
52 | while(true){
53 |
54 | if (queue.isEmpty()) {
55 | // fire onidle events if a callback is provided
56 | if (onidle) {
57 | onidle();
58 | }
59 | if(shuttingDown){
60 | return;
61 | }
62 | }
63 | if (loopLevel < currentLoopLevel) {
64 | return;
65 | }
66 |
67 | exports.processNextEvent(true);
68 |
69 | }
70 |
71 | };
72 |
73 | exports.enqueue = function(task, priority){
74 | if(loopLevel > -1){
75 | queue.put(task); // priority is ignored for now until PriorityBlockingQueue is used
76 | }
77 | };
78 |
79 | exports.hasPendingEvents = function(){
80 | return !queue.isEmpty();
81 | }
82 |
83 | // based on Node's process.unloop();
84 | exports.unloop = function(){
85 | loopLevel--;
86 | };
87 |
88 | exports.shutdown = function(){
89 | shuttingDown = true;
90 | if(queue.isEmpty()){
91 | // if it is empty we need to kick start the event loop to make sure we get into the
92 | // the check for shuttingDown
93 | exports.enqueue(function(){});
94 | }
95 | };
96 |
97 | exports.defaultErrorReporter = function(e){
98 | print((e.rhinoException && e.rhinoException.printStackTrace()) || (e.name + ": " + e.message));
99 | };
100 |
101 |
--------------------------------------------------------------------------------
/engines/rhino/lib/events-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // TODO consolidate API here.
3 | var QE = require("./event-queue");
4 | for (var name in QE) {
5 | exports[name] = QE[name];
6 | }
7 |
8 | exports.setTimeout = function () {
9 | throw "NYI";
10 | };
11 |
12 | exports.setInterval = function () {
13 | throw "NYI";
14 | };
15 |
16 | exports.clearTimeout = function () {
17 | throw "NYI";
18 | };
19 |
20 | exports.clearInterval = function () {
21 | throw "NYI";
22 | };
23 |
24 |
--------------------------------------------------------------------------------
/engines/rhino/lib/http-client-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- isaacs Isaac Schlueter
3 |
4 | var IO = require("io").IO,
5 | HashP = require("hashp").HashP;
6 |
7 | var engine = exports;
8 |
9 | engine.connect = function HttpClient_engine_connect (tx) {
10 | if (tx._isConnected) return;
11 |
12 | var con = java.net.HttpURLConnection(new java.net.URL(tx.url).openConnection());
13 | con.setRequestMethod(tx.method.toUpperCase());
14 |
15 | HashP.forEach(tx.headers, function (h, v) {
16 | con.setRequestProperty(h, v);
17 | });
18 | if (!tx.headers) tx.headers = {};
19 | var cl = HashP.get(tx.headers, "Content-Length") || 0;
20 | if (cl > 0) {
21 | con.setDoOutput(true);
22 | var os = null;
23 | try {
24 | os = con.getOutputStream();
25 | } catch (ex) {}
26 | if (os) {
27 | var writer = new IO(null, con.getOutputStream());
28 | tx.body.forEach(function (piece) {
29 | writer.write(piece);
30 | });
31 | writer.close();
32 | }
33 | }
34 |
35 | try {
36 | con.connect();
37 | } catch (ex) {
38 | // It would be nice to do something clever and special here,
39 | // but I'm not feeling it at the moment.
40 | ex.message = [
41 | "Could not connect to "+tx.url+". Probably a bad hostname.",
42 | ex.message
43 | ].join("\n");
44 | throw ex;
45 | }
46 |
47 | tx._isConnected = true;
48 | var resp = tx._response = {status:200, headers:{}, body:[]};
49 |
50 | // Call this now to trigger the fetch asynchronously.
51 | // This way, if you set up multiple HttpClients, and then call connect()
52 | // on all of them, you'll only wait as long as the slowest one, since
53 | // the streams will start filling up right away.
54 |
55 |
56 | // now pull everything out.
57 | var fields = con.getHeaderFields();
58 | var fieldKeys = fields.keySet().toArray();
59 | for (var i = 0, l = fieldKeys.length; i < l; i ++ ) {
60 | var fieldValue = fields.get(fieldKeys[i]).toArray().join('');
61 | var fieldName = fieldKeys[i];
62 | if (fieldName === null) {
63 | // Something like: HTTP/1.1 200 OK
64 | HashP.set(resp, "status", +(/HTTP\/1\.[01] ([0-9]{3})/.exec(fieldValue)[1]));
65 | // fieldName = "Status";
66 | resp.statusText = fieldValue;
67 | continue;
68 | }
69 | HashP.set(resp.headers, fieldName, fieldValue);
70 | }
71 |
72 | // TODO: Restructure using non-blocking IO to support asynchronous interactions.
73 | // In that case, you could just have a callback that gets each bytestring.
74 | var is = null;
75 | try {
76 | var is = con.getInputStream();
77 | } catch (ex) {
78 | return resp;
79 | }
80 |
81 | // TODO: Should the input stream be rewindable?
82 | var reader = new IO(con.getInputStream(), null);
83 | resp.body = {forEach : function (block) {
84 | var buflen = 1024;
85 | for (
86 | var bytes = reader.read(buflen);
87 | bytes.length > 0;
88 | bytes = reader.read(buflen)
89 | ) block(bytes);
90 | }};
91 |
92 | return resp;
93 | };
94 |
--------------------------------------------------------------------------------
/engines/rhino/lib/http-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var IO = require('./io').IO;
5 |
6 | exports.IO = function (url) {
7 | return new IO(
8 | new java.net.URL(url).openStream(),
9 | null
10 | );
11 | };
12 |
13 |
--------------------------------------------------------------------------------
/engines/rhino/lib/http.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | var FILE = require("file");
5 | var IO = require("io").IO;
6 |
7 | exports.open = function(url, mode, options) {
8 | mode = mode || "b";
9 | options = options || {};
10 |
11 | options.method = options.method || "GET";
12 | options.headers = options.headers || {};
13 |
14 | var connection = new java.net.URL(url).openConnection();
15 | connection.setDoInput(true);
16 | connection.setDoOutput(true);
17 | connection.setRequestMethod(options.method);
18 |
19 | for (var name in options.headers){
20 | connection.addRequestProperty(String(name), String(options.headers[name]));
21 | }
22 |
23 | connection.connect();
24 |
25 | var output = new IO(null, connection.getOutputStream());
26 | var input = null;
27 |
28 | var request = {
29 | status : null,
30 | headers : {},
31 | read : function() {
32 | if (!input) {
33 | output.close();
34 | input = new IO(connection.getInputStream(), null);
35 | this.status = Number(connection.getResponseCode());
36 | this.statusText = String(connection.getResponseMessage() || "");
37 | for (var i = 0; ; i++) {
38 | var key = connection.getHeaderFieldKey(i), value = connection.getHeaderField(i);
39 | if (! key && ! value)
40 | break;
41 | if (key)
42 | this.headers[String(key)] = String(value);
43 | }
44 | }
45 | return input.read.apply(input, arguments);
46 | },
47 | write : function() {
48 | output.write.apply(output, arguments);
49 | return this;
50 | },
51 | flush : function() {
52 | output.flush.apply(output, arguments);
53 | return this;
54 | },
55 | close : function() {
56 | if (output)
57 | output.close();
58 | if (input)
59 | input.close();
60 | return this;
61 | },
62 | copy : IO.prototype.copy
63 | }
64 | return request;
65 | };
66 |
67 | exports.read = function(url) {
68 | var stream = exports.open(url);
69 | try {
70 | return stream.read();
71 | } finally {
72 | stream.close();
73 | }
74 | };
75 |
76 | exports.copy = function(source, target, mode) {
77 | mode = mode || "b";
78 | return FILE.path(target).write(exports.read(source, mode), mode);
79 | };
80 |
--------------------------------------------------------------------------------
/engines/rhino/lib/interpreter.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
4 |
5 | // Prototyping and expermenting with Context Creation and Module
6 | // evaluation, per ECMAScript strawman proposal:
7 | // http://wiki.ecmascript.org/doku.php?id=strawman:modules_primordials
8 |
9 | var Context = exports.Context = function() {
10 | var self = this;
11 |
12 | // TODO: verify this is the correct way to obtain a Context.
13 | // var context = new Packages.org.mozilla.javascript.Context();
14 | function getContext() {
15 | // return context;
16 | return Packages.org.mozilla.javascript.Context.getCurrentContext();
17 | }
18 |
19 | self.global = getContext().initStandardObjects();
20 |
21 | self.eval = function(source) {
22 | source = source || "";
23 | var sourceURL = findSourceURL(source) || "";
24 |
25 | return getContext().evaluateString(
26 | self.global,
27 | source,
28 | sourceURL,
29 | 1,
30 | null
31 | );
32 | };
33 |
34 | self.evalFile = function(sourceURL) {
35 | require("narwhal").deprecated("Context's evalFile() is deprecated in favor of importScript().");
36 | return self.importScript.apply(self, arguments);
37 | };
38 |
39 | self.importScript = function (sourceURL) {
40 | return getContext().evaluateReader(
41 | self.global,
42 | new Packages.java.io.FileReader(sourceURL),
43 | sourceURL,
44 | 1,
45 | null
46 | );
47 | };
48 |
49 | self.importScripts = function () {
50 | for (var i = 0, ii = arguments.length; i < ii; i++) {
51 | self.importScript(arguments[i]);
52 | }
53 | };
54 |
55 | self.Module = function (text, fileName, lineNo) {
56 | return function (inject) {
57 | var names = [];
58 | for (var name in inject)
59 | if (Object.prototype.hasOwnProperty.call(inject, name))
60 | names.push(name);
61 | return getContext().compileFunction(
62 | self.global,
63 | "function(" + names.join(",") + "){" + text + "\n}",
64 | String(fileName),
65 | Number(lineNo) || 1,
66 | null
67 | ).apply(null, names.map(function (name) {
68 | return inject[name];
69 | }));
70 | };
71 | };
72 |
73 | self.Function = function() {
74 | var args = Array.prototype.slice.call(arguments);
75 | var body = args.pop() || "";
76 | var source = "function("+args.join(",")+"){"+body+"/**/\n}";
77 | var sourceURL = findSourceURL(body) || "";
78 |
79 | return getContext().compileFunction(
80 | self.global,
81 | source,
82 | sourceURL,
83 | 1,
84 | null
85 | );
86 | };
87 |
88 | return self;
89 | };
90 |
91 | function findSourceURL(source) {
92 | // based on https://bugs.webkit.org/show_bug.cgi?id=25475#c4
93 | var match = source.match(/.*\s*\/\/\s*@\s*sourceURL\s*=\s*(\S+)\s*/);
94 | if (match)
95 | return match[1];
96 | return null;
97 | }
98 |
99 |
--------------------------------------------------------------------------------
/engines/rhino/lib/md5-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // George Moschovitis
3 |
4 | var binary = require("./binary");
5 |
6 | var JString = Packages.java.lang.String,
7 | JInteger = Packages.java.lang.Integer,
8 | JStringBuffer = Packages.java.lang.StringBuffer,
9 | JMessageDigest = Packages.java.security.MessageDigest;
10 |
11 | exports.hash = function (str) {
12 | var jstr = new JString(str);
13 | var algorithm = JMessageDigest.getInstance("MD5");
14 | algorithm.reset();
15 | algorithm.update(jstr.getBytes());
16 | var bytes = algorithm.digest();
17 | return binary.ByteString(bytes);
18 | };
19 |
20 | // deprecated
21 | //
22 |
23 | var MD5 = exports.MD5 = {};
24 |
25 | MD5.hexdigest = function(str) {
26 | system.log.warn('hexdigest is depreacted, use md5.hash().toString(16)');
27 | var jstr = new JString(str);
28 | var algorithm = JMessageDigest.getInstance("MD5");
29 |
30 | algorithm.reset();
31 | algorithm.update(jstr.getBytes());
32 |
33 | var messageDigest = algorithm.digest();
34 |
35 | var hexString = new JStringBuffer();
36 | for (var i = 0; i < messageDigest.length; i++) {
37 | hexString.append(JInteger.toHexString(0xFF & messageDigest[i]));
38 | }
39 |
40 | return String(hexString.toString());
41 | };
42 |
43 |
--------------------------------------------------------------------------------
/engines/rhino/lib/narwhal/tusk/support.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | exports.supportsEngine = function() {
5 | return true;
6 | }
7 |
--------------------------------------------------------------------------------
/engines/rhino/lib/packages-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- tschaub
4 |
5 | var fs = require('./file');
6 | var system = require('./system');
7 |
8 | /*** analyze
9 | */
10 | exports.analyze = function (analysis, sortedPackages) {
11 | var javaPaths = analysis.javaPaths = []
12 | sortedPackages.forEach(function (packageData) {
13 | /* migration */
14 | if (packageData.jars)
15 | packageData.java = packageData.jars;
16 | /* /migration */
17 | if (typeof packageData.java == 'string')
18 | packageData.java = [packageData.java];
19 | if (!packageData.java)
20 | packageData.java = [];
21 | for (var i = 0; i < packageData.java.length; i++)
22 | packageData.java[i] = packageData.directory.resolve(packageData.java[i]);
23 | /* new approach */
24 | var jarsDirectory = packageData.directory.join('jars');
25 | if (jarsDirectory.isDirectory()) {
26 | jarsDirectory.listPaths().forEach(function (jarDirectory) {
27 | packageData.java.push(jarDirectory);
28 | });
29 | }
30 | javaPaths.unshift.apply(javaPaths, packageData.java);
31 | });
32 | };
33 |
34 | /*** synthesize
35 | */
36 | exports.synthesize = function (analysis) {
37 | exports.addJavaPaths(analysis.javaPaths);
38 | };
39 |
40 | var loader = Packages.java.lang.ClassLoader.getSystemClassLoader();
41 | // so that replacing Packages does not implicitly dispose of the
42 | // only means of creating new Packages objects.
43 |
44 | /*** addJavaPaths
45 | */
46 | exports.addJavaPaths = function addJavaPaths(javaPaths) {
47 | if (!javaPaths || javaPaths.length === 0)
48 | return;
49 | // after reinstalling Packages once, the Packages object
50 | // is no longer a Packages constructor function.
51 | // If that's the case, abandone hope.
52 | if (/*typeof Packages == "object" this no longer works in latest builds of Rhino || */
53 | system.appEngine)
54 | return;
55 |
56 | var context = Packages.org.mozilla.javascript.Context.getCurrentContext();
57 | // check to see if class loader is already in place
58 | if (context.getApplicationClassLoader().getClass() == Packages.java.net.URLClassLoader)
59 | return;
60 |
61 | /* set up jar loader */
62 | var urls = Packages.java.lang.reflect.Array.newInstance(java.net.URL, javaPaths.length);
63 | for (var i = 0; i < javaPaths.length; i++) {
64 | urls[i] = (new java.io.File(javaPaths[i])).toURL();
65 | };
66 | loader = new Packages.java.net.URLClassLoader(urls, loader);
67 |
68 | try {
69 | /* intall jar loader */
70 | Packages.java.lang.Thread.currentThread().setContextClassLoader(loader);
71 | context.setApplicationClassLoader(loader);
72 | // must explicitly be made global when each module has it's own scope
73 | // global.Packages = new Packages(loader);
74 | // re-init the top-level java packages objects with the new classloader
75 | Packages.org.mozilla.javascript.NativeJavaTopPackage.init(context, global, false);
76 | installed = true;
77 | } catch (e) {
78 | print("warning: couldn't install jar loader: " + e);
79 | }
80 | };
81 |
82 |
--------------------------------------------------------------------------------
/engines/rhino/lib/sandbox-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // STATUS: never really worked.
4 |
5 | /* shared, sealed global context */
6 |
7 | var blacklist = [
8 | 'Packages',
9 | 'java',
10 | 'javax',
11 | 'org',
12 | 'net',
13 | 'com',
14 | 'edu',
15 | 'JavaAdapter',
16 | 'JavaImporter',
17 | 'getClass'
18 | ];
19 |
20 | var whitelist = [
21 | 'Array',
22 | 'Boolean',
23 | 'Date',
24 | 'Error',
25 | 'EvalError',
26 | 'Function',
27 | 'Math',
28 | 'Number',
29 | 'Object',
30 | 'RangeError',
31 | 'ReferenceError',
32 | 'InternalError',
33 | 'RegExp',
34 | 'String',
35 | 'SyntaxError',
36 | 'TypeError',
37 | 'URIError',
38 | 'Infinity',
39 | 'NaN',
40 | 'undefined',
41 | 'decodeURI',
42 | 'decodeURIComponent',
43 | 'encodeURI',
44 | 'encodeURIComponent',
45 | 'eval',
46 | 'isFinite',
47 | 'isNaN',
48 | 'parseFloat',
49 | 'parseInt'
50 | ];
51 |
52 | var context = new Packages.org.mozilla.javascript.Context();
53 | var global = context.initStandardObjects(null, true);
54 | for (var i = 0; i < blacklist.length; i++)
55 | delete global[blacklist[i]];
56 | seal(global);
57 |
58 |
59 | /* create module factories */
60 |
61 | exports.evaluate = function (text, id) {
62 | // verify that the script is a program by compiling it as such
63 | context.compileString(text, id, 1, null);
64 | // return a module factory function instead though.
65 | return context.compileFunction(
66 | global,
67 | "function(require,exports,module,system,print){"+text+"}",
68 | id,
69 | 1,
70 | null
71 | );
72 | };
73 |
74 |
--------------------------------------------------------------------------------
/engines/rhino/lib/system.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | var io = require("./io");
5 |
6 | exports.print = function () {
7 | exports.stdout.write(Array.prototype.join.call(arguments, ' ') + "\n").flush();
8 | };
9 |
10 | exports.stdin = new io.TextInputStream(new io.IO(Packages.java.lang.System['in'], null));
11 | exports.stdout = new io.TextOutputStream(new io.IO(null, Packages.java.lang.System.out));
12 | exports.stderr = new io.TextOutputStream(new io.IO(null, Packages.java.lang.System.err));
13 |
14 | exports.args = global.arguments || [];
15 | exports.originalArgs = exports.args.slice(0);
16 |
17 | exports.env = {};
18 |
19 | // fetch ENV variables
20 | var env = Packages.java.lang.System.getenv(),
21 | keyIterator = env.keySet().iterator();
22 | while (keyIterator.hasNext()) {
23 | var key = keyIterator.next();
24 | exports.env[String(key)] = String(env.get(key));
25 | }
26 |
27 | // merge properties over top
28 | var properties = Packages.java.lang.System.getProperties();
29 | keyIterator = properties.keySet().iterator();
30 | while (keyIterator.hasNext()) {
31 | var key = keyIterator.next();
32 | exports.env[String(key)] = String(properties.getProperty(key));
33 | }
34 |
35 |
36 | var securityManager = Packages.java.lang.System.getSecurityManager()
37 | if (securityManager) {
38 | var securityManagerName = securityManager.getClass().getName();
39 | if (/^com.google.app(engine|hosting)./.test(securityManagerName))
40 | exports.appEngine = true;
41 | if (/^com.google.apphosting\./.test(securityManagerName))
42 | exports.appEngineHosting = true;
43 | }
44 |
45 | exports.fs = require('./file');
46 |
47 | // default logger
48 | var Logger = require("./logger").Logger;
49 | exports.log = new Logger(exports.stderr);
50 |
51 |
--------------------------------------------------------------------------------
/engines/rhino/lib/uuid.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriszyp Kris Zyp
3 | // -- tlrobinson Tom Robinson
4 |
5 | exports.randomUUID = function(){
6 | require("narwhal").deprecated("randomUUID is deprecated in favor of uuid");
7 | return String(java.util.UUID.randomUUID());
8 | };
9 |
10 | // compatible with Narwhal's main UUID module
11 | exports.uuid = function(){
12 | return String(java.util.UUID.randomUUID()).toUpperCase();
13 | };
14 |
15 |
--------------------------------------------------------------------------------
/engines/rhino/lib/worker-engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriszyp Kris Zyp
3 |
4 | exports.createEnvironment = function(){
5 | var workerQueue,
6 | workerGlobal = new org.mozilla.javascript.tools.shell.Global();
7 | javaWorkerGlobal = new org.mozilla.javascript.NativeJavaObject(global, workerGlobal, null);
8 | javaWorkerGlobal.init(org.mozilla.javascript.tools.shell.Main.shellContextFactory);
9 | workerGlobal.NARWHAL_HOME = system.prefix;
10 | workerGlobal.NARWHAL_ENGINE_HOME = system.prefix + '/engines/' + system.engine;
11 | // get the path to the bootstrap.js file
12 | var bootstrapPath = system.prefix + '/engines/' + system.engine + "/bootstrap.js";
13 | org.mozilla.javascript.tools.shell.Main.processFile(
14 | org.mozilla.javascript.Context.enter(),
15 | workerGlobal,
16 | bootstrapPath);
17 |
18 | return workerGlobal;
19 | };
20 |
21 | exports.spawn = function(functionToRun, threadName){
22 | var sourceContext = Packages.org.mozilla.javascript.Context.getCurrentContext();
23 | var classLoader = sourceContext.getApplicationClassLoader();
24 | (new java.lang.Thread(function(){
25 | var context = Packages.org.mozilla.javascript.Context.getCurrentContext();
26 | context.setOptimizationLevel(sourceContext.getOptimizationLevel());
27 | context.setLanguageVersion(sourceContext.getLanguageVersion());
28 | context.setApplicationClassLoader(classLoader);
29 | context.getWrapFactory().setJavaPrimitiveWrap(sourceContext.getWrapFactory().isJavaPrimitiveWrap());
30 |
31 | functionToRun();
32 | }, threadName)).start();
33 | };
34 |
35 |
--------------------------------------------------------------------------------
/engines/rhino/lib/zip.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var io = require('io');
5 |
6 | var javaZip = Packages.java.util.zip;
7 | var JavaZipFile = javaZip.ZipFile;
8 | var JavaZipEntry = javaZip.ZipEntry;
9 |
10 | exports.unzip = function (source, target) {
11 | if (!target)
12 | target = system.fs.path(source).absolute().dirname();
13 | target = system.fs.path(target);
14 | var unzip = new exports.Unzip(source);
15 | try{
16 | return unzip.forEach(function (entry) {
17 | var targetPath = target.join(entry.getName());
18 | if (entry.isDirectory())
19 | return;
20 | targetPath.dirname().mkdirs();
21 | targetPath.write(entry.read('b'), 'b');
22 | });
23 | }
24 | finally{
25 | unzip.close();
26 | }
27 | };
28 |
29 | exports.Unzip = function (path) {
30 | this._javaZipFile = JavaZipFile(path);
31 | };
32 |
33 | exports.Unzip.prototype.iterator = function () {
34 | var self = this;
35 | var enumeration = this._javaZipFile.entries();
36 | return {
37 | next: function () {
38 | if (!enumeration.hasMoreElements())
39 | throw StopIteration;
40 | return new exports.Entry(
41 | self._javaZipFile,
42 | enumeration.nextElement()
43 | );
44 | }
45 | };
46 | };
47 |
48 | exports.Unzip.prototype.forEach = function (block, context) {
49 | var iterator = this.iterator();
50 | var next;
51 | while (true) {
52 | try {
53 | next = iterator.next();
54 | } catch (exception) {
55 | break;
56 | }
57 | block.call(context, next);
58 | }
59 | };
60 |
61 | exports.Unzip.prototype.close = function (mode, options) {
62 | this._javaZipFile.close();
63 | };
64 |
65 | exports.Entry = function (javaZipFile, javaZipEntry) {
66 | this._javaZipFile = javaZipFile;
67 | this._javaZipEntry = javaZipEntry;
68 | };
69 |
70 | exports.Entry.prototype.getName = function () {
71 | return String(this._javaZipEntry.getName());
72 | };
73 |
74 | exports.Entry.prototype.isDirectory = function () {
75 | return Boolean(this._javaZipEntry.isDirectory());
76 | };
77 |
78 | exports.Entry.prototype.open = function (mode, options) {
79 | // TODO mode and options negotiation
80 | return new io.IO(this._javaZipFile.getInputStream(this._javaZipEntry));
81 | };
82 |
83 | exports.Entry.prototype.read = function () {
84 | return this.open().read();
85 | };
86 |
87 | exports.Entry.prototype.copy = function (output, mode, options) {
88 | return this.open().copy(output);
89 | };
90 |
91 |
--------------------------------------------------------------------------------
/engines/rhino/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "narwhal-rhino",
3 | "engine": "rhino"
4 | }
5 |
--------------------------------------------------------------------------------
/engines/secure/lib/file.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | for (var name in system.fs) {
5 | if (Object.prototype.hasOwnProperty.call(system.fs, name))
6 | exports[name] = system.fs[name];
7 | }
8 |
9 |
--------------------------------------------------------------------------------
/engines/secure/lib/system.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | for (var name in system) {
5 | if (Object.prototype.hasOwnProperty.call(system, name)) {
6 | exports[name] = system[name];
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/engines/template/bin/narwhal-engine-name:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # get the absolute path of the executable
4 | SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- "$0")
5 |
6 | # resolve symlinks
7 | while [ -h "$SELF_PATH" ]; do
8 | DIR=$(dirname -- "$SELF_PATH")
9 | SYM=$(readlink -- "$SELF_PATH")
10 | SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
11 | done
12 |
13 | NARWHAL_ENGINE_HOME=$(dirname -- $(dirname -- $SELF_PATH))
14 | BOOTSTRAP="$NARWHAL_ENGINE_HOME/bootstrap.js"
15 |
16 | if [ ! "$NARWHAL_HOME" ]; then
17 | NARWHAL_HOME=$(dirname -- $(dirname -- $NARWHAL_ENGINE_HOME))
18 | fi
19 |
20 | export NARWHAL_HOME
21 |
22 | # uses rlwrap (readline wrapper) if present
23 | NARWHAL="$(which rlwrap) narwhal-engine" # TODO replace narwhal-engine with js bin
24 |
25 | # drop into shell if there are no additional arguments
26 | if [ $# -lt 1 ]; then
27 | # FIXME: no way to explicitly drop into shell
28 | $NARWHAL $BOOTSTRAP "$@"
29 | else
30 | MAIN=$(cd -P -- "$(dirname -- "$1")" && pwd -P) && MAIN=$MAIN/$(basename -- "$1" .js)
31 | $NARWHAL $BOOTSTRAP $MAIN "$0" "$@"
32 | fi
33 |
--------------------------------------------------------------------------------
/engines/template/bootstrap.js:
--------------------------------------------------------------------------------
1 | (function (evalGlobal) {
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var read = /*TODO*/; // function(path:string):string
5 |
6 | var isFile = /*TODO*/; // function(path:string):boolean
7 |
8 | var prefix = "/path/to/narwhal"; /*TODO*/
9 | var enginePrefix = "/path/to/engine"; /*TODO*/
10 |
11 | eval(read(prefix + "/narwhal.js"))({
12 | system: {
13 | global: this,
14 | evalGlobal: evalGlobal,
15 | engine: '<<>>', /*TODO*/
16 | engines: ['<<>>', 'default'], /*TODO*/
17 | os: "", /* TODO /\bwindows\b/i for Windows FS support */
18 | // XXX engines may include any number of
19 | // prioritized generic engines like:
20 | // rhino, java, c, v8, default
21 | print: print,
22 | evaluate: function (text) {
23 | // TODO maybe something better here:
24 | return eval(
25 | "(function(require,exports,module,system,print){" +
26 | text +
27 | "/**/\n})"
28 | );
29 | },
30 | prefix: prefix,
31 | prefixes: [prefix],
32 | enginePrefix: enginePrefix,
33 | debug: false,
34 | verbose: false
35 | },
36 | file: {
37 | read: read,
38 | isFile: isFile
39 | }
40 | });
41 |
42 | }).call(this, function () {
43 | return eval(arguments[0]);
44 | });
45 |
--------------------------------------------------------------------------------
/engines/template/lib/system.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | var IO = require("./io").IO;
5 |
6 | exports.stdin = /*TODO*/
7 | exports.stdout = /*TODO*/
8 | exports.stderr = /*TODO*/
9 |
10 | exports.args = [/*TODO*/];
11 |
12 | exports.env = {}; /*TODO*/
13 |
14 | exports.fs = require('./file');
15 |
16 | // default logger
17 | var Logger = require("./logger").Logger;
18 | exports.log = new Logger(exports.stderr);
19 |
20 |
--------------------------------------------------------------------------------
/examples/browser-deployment-jackconfig.js:
--------------------------------------------------------------------------------
1 |
2 | var jackutil = require("jack/utils");
3 |
4 | var app = function (env) {
5 | if (/^../.test(env.PATH_INFO))
6 | return jackutil.responseForStatus(404, env.PATH_INFO);
7 | return {
8 | "status": 200,
9 | "headers": {"Content-type": "text/html"},
10 | "body": [
11 | ""
25 | ]
26 | };
27 | };
28 | app = require("narwhal/server").App(app, {
29 | "debug": true // turn off debug for minification
30 | //"path": "javascript/", // to use an alternate path to the module tree
31 | //"proxy": "http://example.com/.js/", // to use a caching proxy
32 | });
33 | app = require("jack").ContentLength(app);
34 | exports.app = app;
35 |
36 |
--------------------------------------------------------------------------------
/examples/fibonacci-worker.js:
--------------------------------------------------------------------------------
1 | // Adapted from https://developer.mozilla.org/En/Using_web_workers
2 |
3 | var Worker = require("worker").Worker;
4 |
5 | var results = [];
6 |
7 | function resultReceiver(event) {
8 | results.push(parseInt(event.data));
9 | if (results.length == 2) {
10 | postMessage(results[0] + results[1]);
11 | }
12 | }
13 |
14 | function errorReceiver(event) {
15 | throw event.data;
16 | }
17 |
18 | onmessage = function(event) {
19 | var n = parseInt(event.data);
20 |
21 | if (n == 0 || n == 1) {
22 | postMessage(n);
23 | return;
24 | }
25 |
26 | for (var i = 1; i <= 2; i++) {
27 | var worker = new Worker(module.path);
28 | worker.onmessage = resultReceiver;
29 | worker.onerror = errorReceiver;
30 | worker.postMessage(n - i);
31 | }
32 | };
33 |
34 | if (module.id == require.main)
35 | print("Run fibonacci.js instead of fibonacci-worker.js");
36 |
--------------------------------------------------------------------------------
/examples/fibonacci.js:
--------------------------------------------------------------------------------
1 | // Adapted from https://developer.mozilla.org/En/Using_web_workers
2 |
3 | var FILE = require("file"),
4 | Worker = require("worker").Worker;
5 |
6 | var worker = new Worker(FILE.join(FILE.dirname(module.path), "fibonacci-worker.js"));
7 |
8 | worker.onmessage = function(event) {
9 | print("Got: " + event.data);
10 | }
11 |
12 | worker.onerror = function(error) {
13 | print("Worker error: " + error.message);
14 | }
15 |
16 | worker.postMessage(5);
17 |
18 | // event loop
19 | while(true) require("event-queue").nextEvent()();
20 |
--------------------------------------------------------------------------------
/examples/hello:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 | print("Hello, World!");
3 |
--------------------------------------------------------------------------------
/examples/narwhal:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 | var narwhal = require('narwhal');
3 | print(narwhal.LEFT);
4 |
--------------------------------------------------------------------------------
/examples/not-quite-a-quine.js:
--------------------------------------------------------------------------------
1 | system.stdout.write(system.fs.read(module.path)).flush();
2 |
--------------------------------------------------------------------------------
/lib/base16.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- cadorn Christoph Dorn
4 |
5 | var util = require('util');
6 | var binary = require('binary');
7 | var struct = require('struct');
8 |
9 | exports.encode = function (n) {
10 | var length = n.length;
11 | var result = [];
12 | var alphabet = struct.alphabet16Upper;
13 | for (var i = 0; i < length; i++) {
14 | n[i] = n[i] & 0xFF;
15 | result.push(alphabet[(n.charCodeAt(i) >>> 4) & 0xF], alphabet[n.charCodeAt(i) & 0xF]);
16 | }
17 | return result.join('');
18 | };
19 |
20 |
--------------------------------------------------------------------------------
/lib/crc32.js:
--------------------------------------------------------------------------------
1 |
2 | // Copyright 2006-2010 webtoolkit.info
3 | // http://www.webtoolkit.info/
4 |
5 | // ported by:
6 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
7 | // with contributions:
8 | // -- cadorn Christoph Dorn
9 |
10 | var util = require('./util');
11 |
12 | /*** polynomials
13 | */
14 | exports.polynomials = {
15 | 'ieee802_3': 0xEDB88320,
16 | 'castagnoli': 0x82F63B78,
17 | 'kooperman': 0xEB31D82E
18 | };
19 |
20 | /*** Table
21 | */
22 | exports.Table = function (polynomial) {
23 | var term, table = [];
24 | for (var i = 0; i < 256; i++) {
25 | term = i;
26 | for (var j = 0; j < 8; j++) {
27 | if (term & 1)
28 | term = (term >>> 1) ^ polynomial;
29 | else
30 | term = term >>> 1;
31 | }
32 | table[i] = term;
33 | }
34 | return table;
35 | };
36 |
37 | /*** table
38 | */
39 | exports.table = exports.Table(exports.polynomials.ieee802_3);
40 |
41 | /*** hash
42 | returns the crc32 hash for a string as an integer.
43 | */
44 | exports.hash = function (bin, table) {
45 | if (util.no(table))
46 | table = exports.table;
47 | var crc = 0xFFFFFFFF;
48 | for (var i = 0; i < bin.length; i ++) {
49 | var x = bin.charCodeAt(i);
50 | if (x & ~0xFF)
51 | throw new Error(
52 | "crc32 can only encode strings of bytes. " +
53 | "Consider using .toByteString(charset)"
54 | );
55 | crc = (crc >>> 8) ^ table[x ^ (crc & 0xFF)];
56 | }
57 | return ~crc;
58 | };
59 |
60 |
--------------------------------------------------------------------------------
/lib/hash.js:
--------------------------------------------------------------------------------
1 |
2 | // Hash object
3 |
4 | // -- tlrobinson Tom Robinson
5 |
6 | var Hash = exports.Hash = {};
7 |
8 | Hash.merge = function(hash, other) {
9 | var merged = {};
10 | if (hash) Hash.update(merged, hash);
11 | if (other) Hash.update(merged, other);
12 | return merged;
13 | }
14 |
15 | Hash.update = function(hash, other) {
16 | for (var key in other)
17 | hash[key] = other[key];
18 | return hash;
19 | }
20 |
21 | Hash.forEach = function(hash, block) {
22 | for (var key in hash)
23 | block(key, hash[key]);
24 | }
25 |
26 | Hash.map = function(hash, block) {
27 | var result = [];
28 | for (var key in hash)
29 | result.push(block(key, hash[key]));
30 | return result;
31 | }
32 |
--------------------------------------------------------------------------------
/lib/hashp.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | var Hash = require("hash").Hash;
5 |
6 | // HashP : Case Preserving hash, used for headers
7 |
8 | var HashP = exports.HashP = {};
9 |
10 | HashP.get = function(hash, key) {
11 | var ikey = _findKey(hash, key);
12 | if (ikey !== null)
13 | return hash[ikey];
14 | // not found
15 | return undefined;
16 | }
17 |
18 | HashP.set = function(hash, key, value) {
19 | // do case insensitive search, and delete if present
20 | var ikey = _findKey(hash, key);
21 | if (ikey && ikey !== key)
22 | delete hash[ikey];
23 | // set it, preserving key case
24 | hash[key] = value;
25 | }
26 |
27 | HashP.unset = function(hash, key) {
28 | // do case insensitive search, and delete if present
29 | var ikey = _findKey(hash, key),
30 | value;
31 | if (ikey) {
32 | value = hash[ikey];
33 | delete hash[ikey];
34 | }
35 | return value;
36 | }
37 |
38 | HashP.includes = function(hash, key) {
39 | return HashP.get(hash, key) !== undefined
40 | }
41 |
42 | HashP.merge = function(hash, other) {
43 | var merged = {};
44 | if (hash) HashP.update(merged, hash);
45 | if (other) HashP.update(merged, other);
46 | return merged;
47 | }
48 |
49 | HashP.update = function(hash, other) {
50 | for (var key in other)
51 | HashP.set(hash, key, other[key]);
52 | return hash;
53 | }
54 |
55 | HashP.forEach = Hash.forEach;
56 | HashP.map = Hash.map;
57 |
58 | var _findKey = function(hash, key) {
59 | // optimization
60 | if (hash[key] !== undefined)
61 | return key;
62 | // case insensitive search
63 | var key = key.toLowerCase();
64 | for (var i in hash)
65 | if (i.toLowerCase() === key)
66 | return i;
67 | return null;
68 | }
69 |
--------------------------------------------------------------------------------
/lib/html.js:
--------------------------------------------------------------------------------
1 |
2 | // -- gmosx George Moschovitis
3 |
4 | /**
5 | * Escape significant HTML characters as HTML entities.
6 | */
7 | exports.escape = exports.escapeHTML = function(string) {
8 | return String(string)
9 | .replace(/&/g, "&")
10 | .replace(//g, ">");
12 | };
13 |
14 | /**
15 | * Translate basic HTML entities for ampersand, less-than,
16 | * and greater-than to their respective plain characters.
17 | */
18 | exports.unescape = function(string) {
19 | return String(string)
20 | .replace(/&/g, "&")
21 | .replace(/</g, "<")
22 | .replace(/>/g, ">");
23 | };
24 |
25 | /**
26 | * Strip HTML tags.
27 | */
28 | exports.stripTags = function (str) {
29 | return str.replace(/<([^>]+)>/g, "");
30 | }
31 |
32 | // deprecated
33 |
34 | exports.escapeHTML = function (str) {
35 | require("narwhal").deprecation("html.escapeHTML is deprecated.");
36 | return exports.escape(str);
37 | };
38 |
39 |
--------------------------------------------------------------------------------
/lib/http.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- cadorn Christoph Dorn TODO
4 | // -- veged Sergey Berezhnoy TODO
5 |
6 | var ENGINE = require('http-engine');
7 | var FS = require("file");
8 |
9 | exports.open = function (url, mode, options) {
10 | // TODO mode negotiation, particularly for binary vs text buffering
11 | return new ENGINE.IO(url);
12 | };
13 |
14 | exports.read = function (url) {
15 | var stream = exports.open(url);
16 | try {
17 | return stream.read();
18 | } finally {
19 | stream.close();
20 | }
21 | };
22 |
23 | // TODO resolve the source as a file URL
24 | exports.copy = function (source, target, mode) {
25 | mode = mode || 'b';
26 | return FS.path(target).write(exports.read(source, mode), mode);
27 | };
28 |
29 |
--------------------------------------------------------------------------------
/lib/http/fs-store.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var FS = require("file");
5 | var HTTP = require("http");
6 | var URI = require("uri");
7 | var ASSERT = require("assert");
8 |
9 | var Store = exports.Store = function (path) {
10 | this.path = FS.path(path).canonical();
11 | };
12 |
13 | Store.prototype.get = function (url) {
14 | var parsed = URI.parse(url);
15 | if (parsed.scheme == "http") {
16 | ASSERT.ok(parsed.authority, "URI store URI's must be fully qualified");
17 | ASSERT.ok(parsed.root, "URI store URI's must be fully qualified");
18 | return this.path.join.apply(
19 | this.path,
20 | [parsed.authority]
21 | .concat(parsed.directories)
22 | .concat([parsed.file])
23 | );
24 | } else if (parsed.scheme == "file") {
25 | var base = parsed.authorityRoot || parsed.root ?
26 | FS.path('/'):
27 | FS.cwdPath();
28 | return base.join.apply(
29 | base,
30 | parsed.directories.concat([parsed.file])
31 | );
32 | } else {
33 | ASSERT.ok(false, "URI scheme must be http or file");
34 | }
35 | };
36 |
37 | Store.prototype.has = function (url) {
38 | return this.get(url).isFile();
39 | };
40 |
41 | Store.prototype.download = function (url, path) {
42 | if (!path)
43 | path = this.get(url);
44 | path.dirname().mkdirs();
45 | var parsed = URI.parse(url);
46 | if (parsed.scheme == "http")
47 | HTTP.open(url, 'rb').copy(path.open('wb'));
48 | }
49 |
50 | Store.prototype.open = function (url, mode, options) {
51 | var path = this.get(url);
52 | if (!path.isFile())
53 | this.download(url, path);
54 | return path.open(mode, options);
55 | };
56 |
57 | Store.prototype.read = function (url, options) {
58 | var stream = this.open(url, "r", options);
59 | try {
60 | return stream.read();
61 | } finally {
62 | stream.close();
63 | }
64 | };
65 |
66 | if (require.main == module) {
67 | // test
68 | var url = "http://github.com/280north/narwhal/raw/master/catalog.json";
69 | var TUSK = require("narwhal/tusk");
70 | var store = new Store(TUSK.getTuskDirectory().join("http"));
71 | print(store.get('file:here.json'));
72 | //print(store.get(url));
73 | //print(store.read(url));
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/lib/io.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | // IO: engine independent
5 |
6 | var engine = require("io-engine");
7 |
8 | var ByteString = require("./binary").ByteString,
9 | ByteArray = require("./binary").ByteArray,
10 | B_COPY = require("binary-engine").B_COPY;
11 |
12 | for (var name in engine) {
13 | if (Object.prototype.hasOwnProperty.call(engine, name)) {
14 | exports[name] = engine[name];
15 | }
16 | };
17 |
18 | var IO = exports.IO;
19 |
20 | IO.prototype.readChunk = IO.prototype.readChunk || function(length) {
21 | if (typeof length !== "number") length = 1024;
22 |
23 | var buffer = new ByteArray(length);
24 |
25 | var readLength = this.readInto(buffer, length, 0);
26 |
27 | if (readLength <= 0)
28 | return new ByteString();
29 |
30 | return new ByteString(buffer._bytes, 0, readLength);
31 | };
32 |
33 | IO.prototype.read = IO.prototype.read || function(length) {
34 | if (length !== undefined)
35 | return this.readChunk(length);
36 |
37 | var buffers = [],
38 | total = 0;
39 |
40 | while (true) {
41 | var buffer = this.readChunk();
42 | if (buffer.length > 0) {
43 | buffers.push(buffer);
44 | total += buffer.length;
45 | }
46 | else
47 | break;
48 | }
49 |
50 | var buffer = new ByteArray(total),
51 | dest = buffer._bytes,
52 | copied = 0;
53 |
54 | for (var i = 0; i < buffers.length; i++) {
55 | var b = buffers[i],
56 | len = b.length;
57 | B_COPY(b._bytes, b._offset, dest, copied, len);
58 | copied += len;
59 | }
60 |
61 | return new ByteString(dest, 0, copied);
62 | };
63 |
64 | IO.prototype.write = IO.prototype.write || function(object, charset) {
65 | if (object === null || object === undefined || typeof object.toByteString !== "function")
66 | throw new Error("Argument to IO.write must have toByteString() method");
67 |
68 | var binary = object.toByteString(charset);
69 | this.writeInto(binary, 0, binary.length);
70 |
71 | return this;
72 | };
73 |
74 | IO.prototype.puts = function() {
75 | this.write(arguments.length === 0 ? "\n" : Array.prototype.join.apply(arguments, ["\n"]) + "\n");
76 | }
77 |
78 | exports.Peekable = function (input) {
79 | this._input = input;
80 | this._buffer = new exports.StringIO();
81 | };
82 |
83 | exports.Peekable.prototype.read = function (length) {
84 | if (arguments.length == 0)
85 | return this._buffer.read() + this._input.read();
86 | else if (this._buffer.length)
87 | return this._buffer.read(length);
88 | else
89 | return this._input.read(length);
90 | };
91 |
92 | exports.Peekable.prototype.peek = function (length) {
93 | while (this._buffer.length < length) {
94 | var read = this._input.read(length - this._buffer.length);
95 | if (!read.length)
96 | break;
97 | this._buffer.write(read);
98 | }
99 | return this._buffer.substring(0, length);
100 | };
101 |
102 |
--------------------------------------------------------------------------------
/lib/loader/attenuated.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | exports.AttenuatedLoader = function (loader) {
5 | var self = {};
6 |
7 | self.resolve = Object.freeze(function (id, baseId) {
8 | return loader.resolve(id, baseId);
9 | });
10 |
11 | self.fetch = Object.freeze(function (topId) {
12 | if (/\./.test(topId))
13 | throw new Error("Invalid module identifier: " + topId);
14 | return loader.fetch(topId);
15 | });
16 |
17 | self.load = Object.freeze(function (topId, path) {
18 | if (/\./.test(topId))
19 | throw new Error("Invalid module identifier");
20 | return loader.load(topId, path);
21 | });
22 |
23 | self.reload = Object.freeze(function (topId) {
24 | if (/\./.test(topId))
25 | throw new Error("Invalid module identifier");
26 | return loader.reload(topId, path);
27 | });
28 |
29 | return Object.freeze(self);
30 | };
31 |
32 |
--------------------------------------------------------------------------------
/lib/loader/multi.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- tlrobinson Tom Robinson
4 | // -- cadorn Christoph Dorn
5 |
6 | // NOTE: this file is used is the bootstrapping process,
7 | // so any "requires" must be accounted for in narwhal.js
8 |
9 | var FILE = require("file");
10 | var LOADER = require("loader");
11 |
12 | exports.MultiLoader = function (options) {
13 |
14 | var factories = options.factories || {};
15 |
16 | var self = {};
17 | self.paths = options.paths || [];
18 | self.loader = options.loader || LOADER.Loader(options);
19 | self.loaders = options.loaders || [
20 | ["", self.loader],
21 | [".js", self.loader]
22 | ];
23 |
24 | self.resolve = LOADER.resolve;
25 |
26 | self.resolvePkg = function(id, baseId, pkg, basePkg) {
27 | return LOADER.resolvePkg(self, id, baseId, pkg, basePkg);
28 | };
29 |
30 | self.find = function (topId) {
31 | // if it's absolute only search the "root" directory.
32 | // FILE.join() must collapse multiple "/" into a single "/"
33 | var searchPaths = FILE.isAbsolute(topId) ? [""] : self.paths;
34 |
35 | for (var j = 0, jj = self.loaders.length; j < jj; j++) {
36 | var extension = self.loaders[j][0];
37 | var loader = self.loaders[j][1];
38 | for (var i = 0, ii = searchPaths.length; i < ii; i++) {
39 | var path = FILE.join(searchPaths[i], topId + extension);
40 | if (FILE.isFile(path)) {
41 | // now check each extension for a match.
42 | // handles case when extension is in the id, so it's matched by "",
43 | // but we want to use the loader corresponding to the actual extension
44 | for (var k = 0, kk = self.loaders.length; k < kk; k++) {
45 | var ext = self.loaders[k][0];
46 | if (path.lastIndexOf(ext) === path.length - ext.length)
47 | return [self.loaders[k][1], path];
48 | }
49 | throw new Error("shouldn't reach this point!");
50 | }
51 | }
52 | }
53 | throw new Error("require error: couldn't find \"" + topId + '"');
54 | };
55 |
56 | self.load = function (topId, loader, path) {
57 | if (!loader || !path) {
58 | var pair = self.find(topId);
59 | loader = pair[0];
60 | path = pair[1];
61 | }
62 | if (
63 | !Object.prototype.hasOwnProperty.call(factories, topId) ||
64 | (loader.hasChanged && loader.hasChanged(topId, path))
65 | )
66 | self.reload(topId, loader, path);
67 | return factories[topId];
68 | };
69 |
70 | self.reload = function (topId, loader, path) {
71 | if (!loader || !path) {
72 | var pair = self.find(topId);
73 | loader = pair[0];
74 | path = pair[1];
75 | }
76 | loader.reload(topId, path);
77 | factories[topId] = loader.load(topId, path);
78 | };
79 |
80 | self.isLoaded = function (topId) {
81 | return Object.prototype.hasOwnProperty.call(factories, topId);
82 | };
83 |
84 | return self;
85 | };
86 |
87 |
--------------------------------------------------------------------------------
/lib/loader/prefix.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | exports.PrefixLoader = function (prefix, loader) {
5 | var self = this || {};
6 |
7 | self.resolve = function (id, baseId) {
8 | return loader.resolve(id, baseId);
9 | };
10 |
11 | /**** evaluate
12 | */
13 | self.evaluate = function (text, topId) {
14 | return loader.evaluate(text, prefix + topId);
15 | };
16 |
17 | /**** fetch
18 | */
19 | self.fetch = function (topId) {
20 | return loader.fetch(prefix + topId);
21 | };
22 |
23 | /**** load
24 | */
25 | self.load = function (topId) {
26 | return loader.load(prefix + topId);
27 | };
28 |
29 | return self;
30 | };
31 |
32 |
--------------------------------------------------------------------------------
/lib/logger.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | // Logging
5 | //
6 | // FATAL: an unhandleable error that results in a program crash
7 | // ERROR: a handleable error condition
8 | // WARN: a warning
9 | // INFO: generic (useful) information about system operation
10 | // DEBUG: low-level information for developers
11 | // (Stolen from Ruby)
12 | //
13 |
14 | var file = require("file");
15 |
16 | var Logger = exports.Logger = function(output) {
17 | if (typeof output === "string")
18 | this.output = file.open(output, "a");
19 | else
20 | this.output = output;
21 |
22 | this.level = Logger.INFO;
23 | };
24 |
25 | Logger.SEV_LABEL = ["FATAL", "ERROR", "WARN" , "INFO" , "DEBUG"];
26 |
27 | Logger.SEV_LABEL.forEach(function(label, severity) {
28 | Logger[label] = severity;
29 | Logger.prototype[label.toLowerCase()] = function() {
30 | return this.add(severity, this.format(severity, arguments));
31 | };
32 | });
33 |
34 | Logger.prototype.add = function(severity, message, progname) {
35 | if (severity > this.level)
36 | return false;
37 | this.output.print(message || progname);
38 | };
39 |
40 | Logger.prototype.format = function(severity, args) {
41 | return new Date() + " ["+Logger.SEV_LABEL[severity].toLowerCase()+"] " +Array.prototype.join.apply(args, [" "]).replace(/\n/g, "");
42 | };
43 |
44 |
--------------------------------------------------------------------------------
/lib/narwhal/json.md:
--------------------------------------------------------------------------------
1 |
2 | JA: normal JSON
3 | [[1,2,3],[4,5,6]]
4 |
5 | JA': abnormal multi-line JSON
6 | [[1,2,3],
7 | [4,5,6]]
8 |
9 | JAR: normal reversed java array
10 | [[3,2,1],[6,5,4]]
11 |
12 | JOA: deep JSON config file
13 | {
14 | "values": [
15 | [1,2,3],
16 | [4,5,6]
17 | ]
18 | }
19 |
20 | JAO: a deep JSON array of objects
21 |
22 | [
23 | {"a": 1, "b": 2, "c": 3},
24 | {"a": 4, "b": 5, "c": 6}
25 | ]
26 |
27 | JAS: a JSON array of sums
28 |
29 | [6, 15]
30 |
31 | JP: pretty JSON, t = 4
32 |
33 | [
34 | [1,2,3],
35 | [4,5,6]
36 | ]
37 |
38 | JL: lines of JSON
39 | [1,2,3]
40 | [4,5,6]
41 |
42 | J0: null-terminated lines of JSON
43 |
44 | [1,2,3]\0[4,5,6]\0
45 |
46 | SL: lines of toString
47 |
48 | 1,2,3
49 | 4,5,6
50 |
51 | S0: null terminated lines of toString
52 |
53 | 1,2,3\04,5,6\0
54 |
55 | flat lines of JSON values
56 | 1
57 | 2
58 | 3
59 | 4
60 | 5
61 | 6
62 |
63 | flat lines of JSON
64 | "2"
65 | "3"
66 | "4"
67 | "5"
68 | "6"
69 |
70 | UAA: unix records
71 |
72 | 1:2:3
73 | 4:5:6
74 |
75 | Cookbook
76 | ========
77 |
78 | JOA -> JA: extracting a JSON array form a JSON object with an array
79 | -N}e{P
80 |
81 | -N _.read()
82 | -} JSON.decode(_)
83 | -e statement(_) "_.values"
84 | -{ JSON.encode(_)
85 | -P print(_)
86 |
87 | JA -> JOA: creating a JSON object with an array from a JSON array
88 | -N}x{P
89 |
90 | -N _.read()
91 | -} JSON.decode(_)
92 | -x expression(_) "{values: _}"
93 | -{ JSON.encode(_)
94 | -P print(_)
95 |
96 | JAO -> JA: converting objects to arrays
97 | -N}f{P
98 |
99 | -N _.read()
100 | -} JSON.decode(_)
101 | -f _.map(select) "a,b,c"
102 | -{ JSON.encode(_)
103 | -P print(_)
104 |
105 | JAR -> JA
106 | -N}
107 |
108 | -N _.read()
109 | -} JSON.decode(_)
110 | -f _.map(select) "3,2,1"
111 | -{ JSON.encode(_)
112 | -P print(_)
113 |
114 | JA -> JAS: calculating the sum of each array
115 | -N}l{P
116 |
117 | -N _.read()
118 | -} JSON.decode(_)
119 | -l _.map(lambda) "a,b,c" "a+b+c"
120 | -{ JSON.encode(_)
121 | -P print(_)
122 |
123 | JA' -> JA: normalizing an abnormal JSON file
124 | -N}{P
125 |
126 | -N _.read()
127 | -} JSON.decode(_)
128 | -{ JSON.encode(_)
129 | -P print(_)
130 |
131 | JL -> J
132 | -}]{P
133 |
134 | -} _.map(JSON.decode)
135 | -] [array(_)]
136 | -{ JSON.encode(_)
137 | -P print(_)
138 |
139 | J -> JL
140 | -N}{p
141 |
142 | -N _.read()
143 | -} JSON.decode(_)
144 | -{ _.map(JSON.encode)
145 | -p _.forEach(print)
146 |
147 | J -> SL
148 | -N}p
149 |
150 | -N _.read()
151 | -} JSON.decode(_)
152 | -p _.forEach(print)
153 |
154 | SL -> JA
155 | -ne]{P
156 |
157 | -ne _.map(expression) "_.split(/,/)"
158 | -] [array(_)]
159 | -{ JSON.encode(_)
160 | -P print(_)
161 |
162 | UAA -> JA
163 | -d]{P
164 |
165 | -d _.map(split) ":"
166 | -] [array(_)]
167 | -{ JSON.encode(_)
168 | -P print(_)
169 |
170 | UAA -> JAR
171 | -d]f{P
172 |
173 | -d _.map(split) ":"
174 | -] [array(_)]
175 | -f _.map(select) "3,2,1"
176 | -{ JSON.encode(_)
177 | -P print(_)
178 |
179 |
--------------------------------------------------------------------------------
/lib/narwhal/repl-worker.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriszyp Kris Zyp
3 |
4 | var system = require("system");
5 |
6 | try { var readline = require("readline").readline; } catch (e) {}
7 | try { var Narcissus = require("narcissus/parse"); } catch (e) {}
8 |
9 | var util = require('util'),
10 | queue = require("event-queue");
11 |
12 | var PROMPT_NORMAL = "js> ",
13 | PROMPT_INCOMPLETE = " > "
14 |
15 | var buffer = "";
16 |
17 | function readln(input) {
18 | while (!(/\n/).test(buffer))
19 | buffer += input.read(100).toString();
20 |
21 | var lines = buffer.split("\n"),
22 | line = lines.shift();
23 |
24 | buffer = lines.join("\n");
25 |
26 | return line
27 | }
28 | global.onconnect = function (e) {
29 | global.onconnect = null; // only connect to one worker
30 |
31 | var buffer = "",
32 | bufferedLines = [],
33 | pendingLines = [];
34 |
35 | system.stdout.write(PROMPT_NORMAL);
36 | system.stdout.flush();
37 |
38 | while (true) {
39 | var line = readline ? readline() : system.stdin.readLine();
40 | if (!line) {
41 | system.stdout.write("\n");
42 | system.stdout.flush();
43 | break;
44 | }
45 |
46 | line = util.trimEnd(line);
47 | var text = pendingLines.join("\n") + "\n" + line;
48 | if (line == "" || !incomplete(text)) {
49 |
50 | pendingLines = [];
51 | e.port.postMessage(text);
52 | queue.processNextEvent(true);// wait for it to be processed before showing the next prompt
53 |
54 | } else
55 | pendingLines.push(line);
56 |
57 | if (pendingLines.length > 0)
58 | system.stdout.write(PROMPT_INCOMPLETE);
59 | else
60 | system.stdout.write(PROMPT_NORMAL);
61 | system.stdout.flush();
62 |
63 | }
64 | }
65 |
66 | function incomplete(text) {
67 | if (!Narcissus)
68 | return false;
69 |
70 | var incomp = true;
71 | try {
72 | var t = new Narcissus.Tokenizer(text);
73 | var x = new Narcissus.CompilerContext(false);
74 | var n = Narcissus.Script(t, x);
75 | incomp = !t.done;
76 | } catch (e) {
77 | if (!t.done) {
78 | print(e);
79 | return false;
80 | }
81 | }
82 | return incomp;
83 | }
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/lib/narwhal/repl.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 | // -- kriszyp Kris Zyp
4 |
5 | var system = require("system"),
6 | util = require('util'),
7 | SharedWorker = require("worker").SharedWorker,
8 | queue = require("event-queue"),
9 | replEval = eval;
10 |
11 | exports.repl = function(dontEnterEventLoop) {
12 | var replWorker = new SharedWorker("narwhal/repl-worker", "repl-worker");
13 | // the worker receives the input from the users and posts the inputs back to us
14 | replWorker.port.onmessage = function(message){
15 | // got a command from the console
16 | try {
17 | var result = replEval(message.data);
18 | var repr = util.repr(result);
19 | if (repr.length > 76 || /\n/.test(repr))
20 | repr = String(result);
21 | if (!util.no(result)) {
22 | system.stdout.write(repr + '\n');
23 | system.stdout.flush();
24 | global._ = result;
25 | }
26 |
27 | } catch (e) {
28 | system.stdout.write(" exception from uncaught JavaScript throw: " + e + "\n");
29 | system.stdout.flush();
30 | }
31 | replWorker.port.postMessage(""); // just signal we are done displaying the result
32 | };
33 | if(!dontEnterEventLoop){
34 | // now enter the event loop
35 | queue.enterEventLoop();
36 | }
37 | };
38 |
39 | // fix quit(), I have no idea why the Rhino shell provided quit doesn't work, but it doesn't
40 | quit = function(code){
41 | java.lang.System.exit(code || 0);
42 | };
43 |
44 | if (module.id == require.main)
45 | exports.repl();
46 |
47 |
--------------------------------------------------------------------------------
/lib/narwhal/server-test.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var Q = require("ref-send");
5 | Q.when(require.async("util"), function (util) {
6 | print("Hello, World!");
7 | print(util.keys({"a": 10, "b": 20}).join(', '));
8 | alert(util.upper('hi'));
9 | });
10 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/bin.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var util = require('util');
5 | var tusk = require('../../tusk');
6 | var args = require('args');
7 |
8 | var parser = exports.parser = new args.Parser();
9 |
10 | parser.help('lists all packaged executables');
11 |
12 | parser.action(function (options) {
13 | });
14 |
15 |
16 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/bundle.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/catalog.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var util = require("util");
6 | var args = require("args");
7 |
8 | var parser = exports.parser = new args.Parser();
9 |
10 | parser.help('lists all packages in the catalog');
11 |
12 | parser.action(function (options) {
13 | var self = this;
14 | if (!tusk.getCatalogPath().isFile())
15 | require('./update').update.call(this, options);
16 | util.forEachApply(tusk.readCatalog().packages, function (name, info) {
17 | name = info.name || name;
18 | self.print(
19 | "\0green(" + name + "\0)" +
20 | (info.description ? ": " + info.description : "")
21 | );
22 | });
23 | });
24 |
25 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/clone.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var os = require("os");
6 | var util = require("util");
7 | var args = require("args");
8 |
9 | var parser = exports.parser = new args.Parser();
10 |
11 | parser.help('clones a package from its version control system.')
12 |
13 | parser.args('package');
14 |
15 | parser.option('-o', '--owner', 'owner')
16 | .help("clone from the owner's repository")
17 | .bool()
18 | .inverse();
19 |
20 | parser.option('-u', '--user', 'user')
21 | .help('overrides the user name from which to clone the package')
22 | .set();
23 |
24 |
25 | parser.action(function (options) {
26 | exports.clone.call(this, options, options.args);
27 | });
28 |
29 | exports.clone = function (options, names) {
30 | var self = this;
31 | if (!util.len(names))
32 | throw new Error("Package name required");
33 | var packagesDirectory = tusk.getPackagesDirectory();
34 | var sources = tusk.readSources().sources;
35 | var catalog = tusk.readCatalog().packages;
36 | var owner = options.owner;
37 | names.forEach(function (name) {
38 | if (!util.has(sources, name))
39 | throw new Error("Package does not exist: " + name);
40 | var source = util.get(sources, name);
41 | if (source.type !== "github")
42 | throw new Error("Package " + util.enquote(name) + " is not a Github package.");
43 | });
44 | names.forEach(function (name) {
45 | var source = util.get(sources, name);
46 | var targetPath = packagesDirectory.join(name);
47 | var githubName = util.get(source, 'name', name);
48 | var user = options.user || source.user;
49 | var command = [
50 | 'git',
51 | 'clone',
52 | owner ?
53 | (
54 | 'git@github.com:' + user +
55 | '/' + githubName + '.git'
56 | ):
57 | (
58 | 'git://github.com/' +
59 | user + '/' + githubName + '.git'
60 | ),
61 | targetPath
62 | ];
63 | self.print('\0cyan(' + command.map(function (term) {
64 | var enquoted = os.enquote(term);
65 | if (enquoted != "'" + term + "'")
66 | return enquoted;
67 | return term;
68 | }).join(' ') + '\0)');
69 | if (os.system(command))
70 | throw "'" + command.join(" ") + "' failed";
71 | require("./install").finishInstall(targetPath);
72 | });
73 | };
74 |
75 | parser.helpful();
76 |
77 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/consolidate.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var util = require("util");
6 | var args = require("args");
7 | var fs = require("file");
8 | var packages = require("packages");
9 |
10 | var parser = exports.parser = new args.Parser();
11 |
12 | parser.help('consolidates all installed packages into the current sea.');
13 |
14 | parser.action(function (options) {
15 | var self = this;
16 | var packagesDirectory = tusk.getPackagesDirectory();
17 | util.forEachApply(util.items(packages.catalog), function (name, info) {
18 | var target = packagesDirectory.join(name);
19 | if (!target.exists()) {
20 | fs.symlink(info.directory, target);
21 | self.print(target + ' -> ' + info.directory);
22 | }
23 | });
24 | });
25 |
26 | parser.helpful();
27 |
28 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/engine.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var system = require('system');
5 | var os = require('os');
6 | var fs = require('file');
7 | var util = require('util');
8 | var tusk = require('../../tusk');
9 | var args = require('args');
10 |
11 | var parser = exports.parser = new args.Parser();
12 |
13 | parser.help('selects a engine for the current "sea"');
14 |
15 | parser.arg('engine').optional();
16 |
17 | parser.action(function (options) {
18 | var packages = require("packages");
19 |
20 | var self = this;
21 | var directory = tusk.getDirectory();
22 | var enginesDirectory = directory.join('engines');
23 | if (options.args.length == 0) {
24 | enginesDirectory.list().forEach(function (engineName) {
25 | self.print(engineName);
26 | });
27 | } else {
28 | var engine = options.args.shift();
29 | if (!util.has(packages.engines, engine))
30 | throw new Error("No such engine " + util.enquote(engine));
31 | var narwhalConf = directory.join('narwhal.conf');
32 | narwhalConf.write(
33 | 'NARWHAL_ENGINE=' +
34 | os.enquote(engine) + "\n" +
35 | 'NARWHAL_ENGINE_HOME=' +
36 | os.enquote(
37 | packages.engines[engine].directory.from(
38 | fs.path(system.prefix).join('')
39 | )
40 | ) + "\n"
41 | );
42 | }
43 | });
44 |
45 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/freeze.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/init.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var system = require("system");
5 | var fs = require("file");
6 | var json = require("json");
7 | var util = require("util");
8 | var args = require("args");
9 | var parser = exports.parser = new args.Parser();
10 |
11 | parser.help('initializes a Narwhal package/project directory');
12 |
13 | parser.option('--name', 'name').def("").set();
14 | parser.option('--author', 'author').def("").set();
15 | parser.option('--dependency', 'dependencies').push();
16 | parser.option('--contributor', 'contributors').push();
17 |
18 | parser.action(function (options, parentOptions) {
19 | parentOptions.acted = true;
20 | var packageInfo = {};
21 | var path;
22 | if (options.args.length && !/^-/.test(options.args[0]))
23 | path = options.args.shift();
24 | else
25 | path = fs.cwd();
26 | util.update(packageInfo, options);
27 | delete packageInfo.args;
28 | delete packageInfo.command;
29 | path = fs.path(path).absolute();
30 | print(path);
31 | path.join('.tusk').mkdirs();
32 | path.join('bin').mkdirs();
33 | path.join('lib').mkdirs();
34 |
35 | var sea = path.join('bin', 'sea');
36 | fs.path(system.prefix).join('bin', 'sea').copy(sea);
37 | sea.chmod(0755);
38 |
39 | var activate = path.join('bin', 'activate.bash');
40 | fs.path(system.prefix).join('bin', 'activate.bash')
41 | .copy(activate);
42 | activate.relative().symlink(activate.resolve('activate'));
43 |
44 | path.join('README').touch();
45 | path.join('narwhal.conf')
46 | .write('NARWHAL_DEFAULT_ENGINE=' + system.engine);
47 | var packagePath = path.join('package.json');
48 | if (packagePath.isFile())
49 | util.complete(
50 | packageInfo,
51 | json.decode(packagePath.read({charset:'utf-8'}))
52 | );
53 | packagePath.write(
54 | json.encode(packageInfo, null, 4),
55 | {charset:'utf-8'}
56 | );
57 | });
58 |
59 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/list.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var util = require("util");
6 | var args = require("args");
7 | var packages = require("packages");
8 |
9 | var parser = exports.parser = new args.Parser();
10 |
11 | parser.help('lists all installed packages');
12 |
13 | parser.action(function (options) {
14 | var self = this;
15 | Object.keys(packages.catalog).forEach(function (name) {
16 | self.print(
17 | name + ' \0magenta(' +
18 | packages.catalog[name].directory + '\0)'
19 | );
20 | });
21 | });
22 |
23 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/orphans.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/reheat.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var install = require('./install');
6 | var util = require("util");
7 | var args = require("args");
8 | var packages = require('packages');
9 | var parser = exports.parser = new args.Parser();
10 |
11 | parser.help('reconsistutes the exact versions of all dependencies from a frozen project');
12 |
13 | parser.action(function (options, name) {
14 | var names = packages.root.dependencies || [];
15 | install.install.call(this, options, names);
16 | });
17 |
18 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/remove.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var tusk = require("../../tusk");
5 | var util = require("util");
6 | var args = require("args");
7 | var parser = exports.parser = new args.Parser();
8 |
9 | parser.help('removes the local copy of package');
10 |
11 | parser.action(function (options) {
12 | var names = options.args;
13 | });
14 |
15 | exports.remove = function () {
16 | };
17 |
18 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/update.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var UPDATE = require("../update");
5 | var ARGS = require("args");
6 | var FS = require("file");
7 |
8 | var parser = exports.parser = new ARGS.Parser();
9 |
10 | parser.args("PACKAGE");
11 |
12 | parser.help('downloads the newest package catalog');
13 |
14 | parser.option('-c', '--use-cache')
15 | .help("configures to use already downloaded files when possible")
16 | .set(true);
17 |
18 | parser.option('-i', '--input')
19 | .help("specifies an alternate location to read the input catalog sources")
20 | .set();
21 |
22 | parser.option('-o', '--output')
23 | .help("specifies an alternate location to write the output catalog")
24 | .set();
25 |
26 | parser.option('-d', '--default', 'useDefaultSources')
27 | .help("use default sources instead of $SEA/.tusk/sources.json")
28 | .set(true);
29 |
30 | parser.helpful();
31 |
32 | parser.action(function (options) {
33 | var policy = {};
34 | policy.useCache = options.useCache;
35 | policy.input = options.input && FS.path(options.input);
36 | policy.output = options.output && FS.path(options.output);
37 | policy.useDefaultSources = options.useDefaultSources;
38 | if (!options.args.length) {
39 | UPDATE.update(policy);
40 | } else {
41 | UPDATE.updatePackages(options.args, policy);
42 | }
43 | });
44 |
45 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/commands/upgrade.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/lib/narwhal/tusk/support.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson
3 |
4 | exports.supportsEngine = function() {
5 | // deprecated
6 | if (require("system").supportsTusk != undefined) {
7 | require("narwhal").deprecated("system.supportsTusk deprecated in favor of supportsEngine() function in 'narwhal/tusk/support' module.");
8 | return require("system").supportsTusk;
9 | }
10 |
11 | // attempt to feature detect the things needed by tusk
12 | var hasHttp = false, hasUnzip = false;
13 | try { hasHttp = !!require("http").open; } catch (e) {}
14 | try { hasUnzip = !!require("zip").Unzip; } catch (e) {}
15 |
16 | return hasHttp && hasUnzip;
17 | }
18 |
--------------------------------------------------------------------------------
/lib/test/assert.js:
--------------------------------------------------------------------------------
1 |
2 | // Tom Robison
3 |
4 | var equiv = require("./equiv").equiv,
5 | jsDump = require("./jsdump").jsDump,
6 | util = require("../util");
7 |
8 | var assert = exports;
9 |
10 | function fail(message) {
11 | throw new AssertionError({
12 | "message": message
13 | });
14 | }
15 |
16 | assert.isTrue = function(assertion, message) {
17 | if (assertion !== true)
18 | fail((message || "") + "\nExpected true." +
19 | "\nActual = " + assertion);
20 | }
21 |
22 | assert.isFalse = function(assertion, message) {
23 | if (assertion !== false)
24 | fail((message || "") + "\nExpected false." +
25 | "\nActual = " + assertion);
26 | }
27 |
28 | assert.isNull = function(assertion, message) {
29 | if (assertion !== null)
30 | fail((message || "") + "\nExpected null." +
31 | "\nActual = " + assertion);
32 | }
33 |
34 | assert.isNaN = function(assertion, message) {
35 | if (!isNaN(assertion))
36 | fail((message || "") + "\nExpected NaN." +
37 | "\nActual = " + assertion);
38 | }
39 |
40 | assert.isEqual = function(expected, actual, message) {
41 | if (expected !== actual)
42 | fail((message || "") + "\nExpected equal to = " + jsDump.parse(expected) +
43 | "\nActual = " + jsDump.parse(actual));
44 | }
45 |
46 | assert.is = function (expected, actual, message) {
47 | if (!util.is(expected, actual))
48 | fail((message || "") + "\nExpected identical = " + jsDump.parse(expected) +
49 | "\nActual = " + jsDump.parse(actual));
50 | };
51 |
52 | assert.isSame = function(expected, actual, message) {
53 | if (!equiv(expected, actual))
54 | fail((message || "") + "\nExpected same as = " + jsDump.parse(expected) +
55 | "\nActual = " + jsDump.parse(actual));
56 | }
57 |
58 | assert.eq = function (expected, actual, message) {
59 | if (!util.eq(expected, actual))
60 | fail((message || "") + "\nExpected equal = " + jsDump.parse(expected) +
61 | "\nActual = " + jsDump.parse(actual));
62 | };
63 |
64 |
65 | assert.isDiff = function(expected, actual, message) {
66 | if (equiv(expected, actual))
67 | fail((message || "") + "\nExpected different than = " + jsDump.parse(expected) +
68 | "\nActual = " + jsDump.parse(actual));
69 | }
70 |
71 | assert.throwsError = function(block, type, message) {
72 | var threw = false,
73 | exception = null;
74 |
75 | try {
76 | block();
77 | } catch (e) {
78 | threw = true;
79 | exception = e;
80 | }
81 |
82 | if (!threw)
83 | fail("Expected exception" + (message ? ": " + message : ""));
84 |
85 | if (type !== undefined && !(exception instanceof type))
86 | fail("Expected exception type '"+type+
87 | "', actually '"+exception+"'" + (message ? ": " + message : ""));
88 | }
89 |
90 | var AssertionError = exports.AssertionError = require("assert").AssertionError;
91 |
92 | AssertionError.prototype = new Error();
93 |
--------------------------------------------------------------------------------
/lib/unload.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var observers = [];
5 |
6 | exports.when = function (observer) {
7 | observers.unshift(observer);
8 | };
9 |
10 | exports.send = function () {
11 | observers.forEach(function (observer) {
12 | observer();
13 | });
14 | };
15 |
16 |
--------------------------------------------------------------------------------
/lib/utf8.js:
--------------------------------------------------------------------------------
1 |
2 | // ported by Kris Kowal
3 |
4 | var binary = require('./binary');
5 |
6 | /*** encode
7 | converts a Unicode character string into a UTF-8
8 | character stream.
9 | */
10 | exports.encode = function (string) {
11 | string = string.replace(/\r\n/g,"\n");
12 | var utftext = [];
13 |
14 | for (var n = 0; n < string.length; n++) {
15 |
16 | var c = string.charCodeAt(n);
17 |
18 | if (c < 128) {
19 | utftext.push(c);
20 | }
21 | else if((c > 127) && (c < 2048)) {
22 | utftext.push((c >> 6) | 192);
23 | utftext.push((c & 63) | 128);
24 | }
25 | else {
26 | utftext.push((c >> 12) | 224);
27 | utftext.push(((c >> 6) & 63) | 128);
28 | utftext.push((c & 63) | 128);
29 | }
30 |
31 | }
32 |
33 | return binary.ByteString(utftext);
34 | };
35 |
36 | /*** decode
37 | Converts a UTF-8 character string into a
38 | Unicode character string.
39 | */
40 | exports.decode = function (utftext) {
41 | var string = "";
42 | var i = 0;
43 | var c = c1 = c2 = 0;
44 |
45 | while (i < utftext.length) {
46 |
47 | c = utftext.charCodeAt(i);
48 |
49 | if (c < 128) {
50 | string += String.fromCharCode(c);
51 | i++;
52 | } else if ((c > 191) && (c < 224)) {
53 | c2 = utftext.charCodeAt(i+1);
54 | string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
55 | i += 2;
56 | } else {
57 | c2 = utftext.charCodeAt(i+1);
58 | c3 = utftext.charCodeAt(i+2);
59 | string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
60 | i += 3;
61 | }
62 | }
63 |
64 | return string;
65 | };
66 |
67 |
--------------------------------------------------------------------------------
/lib/uuid.js:
--------------------------------------------------------------------------------
1 |
2 | // ported by Tom Robison
3 |
4 | /*
5 | Based on Math.uuid.js 1.4 by Robert Kieffer
6 |
7 | ----
8 | Copyright (c) 2008, Robert Kieffer
9 | All rights reserved.
10 |
11 | Redistribution and use in source and binary forms, with or without
12 | modification, are permitted provided that the following conditions are met:
13 |
14 | * Redistributions of source code must retain the above copyright notice,
15 | this list of conditions and the following disclaimer.
16 | * Redistributions in binary form must reproduce the above copyright
17 | notice, this list of conditions and the following disclaimer in the
18 | documentation and/or other materials provided with the distribution.
19 | * Neither the name of Robert Kieffer nor the names of its contributors
20 | may be used to endorse or promote products derived from this software
21 | without specific prior written permission.
22 |
23 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 | POSSIBILITY OF SUCH DAMAGE.
34 |
35 | */
36 |
37 |
38 |
39 | /*
40 | * Generate a random uuid.
41 | *
42 | * USAGE: uuid.uuid(length, radix)
43 | * length - the desired number of characters
44 | * radix - the number of allowable values for each character.
45 | *
46 | * EXAMPLES:
47 | * // No arguments - returns RFC4122, version 4 ID
48 | * >>> Math.uuid()
49 | * "92329D39-6F5C-4520-ABFC-AAB64544E172"
50 | *
51 | * // One argument - returns ID of the specified length
52 | * >>> Math.uuid(15) // 15 character ID (default base=62)
53 | * "VcydxgltxrVZSTV"
54 | *
55 | * // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
56 | * >>> Math.uuid(8, 2) // 8 character ID (base=2)
57 | * "01001010"
58 | * >>> Math.uuid(8, 10) // 8 character ID (base=10)
59 | * "47473046"
60 | * >>> Math.uuid(8, 16) // 8 character ID (base=16)
61 | * "098F4D35"
62 | */
63 |
64 |
65 | var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
66 | exports.uuid = function (len, radix) {
67 | var chars = CHARS, uuid = [], rnd = Math.random;
68 | radix = radix || chars.length;
69 |
70 | if (len) {
71 | // Compact form
72 | for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix];
73 | } else {
74 | // rfc4122, version 4 form
75 | var r;
76 |
77 | // rfc4122 requires these characters
78 | uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
79 | uuid[14] = '4';
80 |
81 | // Fill in random data. At i==19 set the high bits of clock sequence as
82 | // per rfc4122, sec. 4.1.5
83 | for (var i = 0; i < 36; i++) {
84 | if (!uuid[i]) {
85 | r = 0 | rnd()*16;
86 | uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
87 | }
88 | }
89 | }
90 |
91 | return uuid.join('');
92 | };
93 |
--------------------------------------------------------------------------------
/local.json.template:
--------------------------------------------------------------------------------
1 | {"packages": ["packages", ".."]}
2 |
--------------------------------------------------------------------------------
/narwhal.conf.template:
--------------------------------------------------------------------------------
1 |
2 | # If a debugger is available for your engine, use it?
3 | #NARWHAL_DEBUGGER=1
4 |
5 | # Alternate engines
6 |
7 | # Rhino
8 | #NARWHAL_DEFAULT_ENGINE="rhino"
9 |
10 | # JavaScript Core
11 | #NARWHAL_ENGINE="jsc"
12 | #NARWHAL_ENGINE_HOME="packages/jsc"
13 |
14 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "narwhal",
3 | "version": "0.2.2",
4 | "description": "A general purpose JavaScript platform",
5 | "keywords": ["javascript", "engine", "platform"],
6 | "author": "Tom Robinson (http://tlrobinson.net/) ",
7 | "contributors": [
8 | "Tom Robinson (http://tlrobinson.net/) ",
9 | "Kris Kowal (http://askawizard.blogspot.com/) ",
10 | "George Moschovitis (http://blog.gmosx.com/)",
11 | "Kevin Dangoor (http://www.blueskyonmars.com/)",
12 | "Hannes Wallnöfer",
13 | "Sébastien Pierre",
14 | "Irakli Gozalishvili (http://rfobic.wordpress.com/)",
15 | "Christoph Dorn (http://www.christophdorn.com/)",
16 | "Zach Carter",
17 | "Nathan L. Smith",
18 | "Jan Varwig",
19 | "Mark Porter",
20 | "Isaac Z. Schlueter (http://blog.izs.me/)",
21 | "Kris Zyp (http://www.sitepen.com/blog/author/kzyp/)",
22 | "Nathan Stott (http://nathan.whiteboard-it.com) ",
23 | "Toby Ho (http://tobyho.com) "
24 | ],
25 | "lib": ["lib"],
26 | "lean": {
27 | "include" : [
28 | "engines/default/**/*",
29 | "engines/rhino/bootstrap.js",
30 | "engines/rhino/lib/**/*",
31 | "engines/rhino/package.json",
32 | "lib/**/*",
33 | "narwhal.js",
34 | "package.json"
35 | ]
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/packages/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore all
2 |
3 | /*
4 |
5 | # except for
6 |
7 | !/.gitignore
8 |
9 | !/readline
10 |
--------------------------------------------------------------------------------
/packages/readline/engines/default/lib/readline.js:
--------------------------------------------------------------------------------
1 |
2 | exports.readline = function() {
3 | return system.stdin.readLine();
4 | }
5 |
--------------------------------------------------------------------------------
/packages/readline/engines/rhino/lib/readline.js:
--------------------------------------------------------------------------------
1 | // use the Rhino shell, in case stdin is coming from the debugger GUI (this will still use jline)
2 | var reader = new java.io.BufferedReader(
3 | new java.io.InputStreamReader(
4 | new org.mozilla.javascript.NativeJavaObject(
5 | global, org.mozilla.javascript.tools.shell.Main.global, null).
6 | getIn(), "UTF-8"));
7 |
8 | exports.readline = function() {
9 | var line = reader.readLine();
10 | if(line === null){
11 | // jline will fail in eclipse, revert to the default impl
12 | exports.readline = function(){
13 | return system.stdin.readLine();
14 | };
15 | return exports.readline();
16 | }
17 |
18 | return String(line);
19 | }
20 |
--------------------------------------------------------------------------------
/packages/readline/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "readline",
3 | "author": "Tom Robinson",
4 | "dependencies": ["narwhal"]
5 | }
6 |
--------------------------------------------------------------------------------
/tests/all-tests.js:
--------------------------------------------------------------------------------
1 |
2 | exports.testURI = require("./uri");
3 | exports.testQS = require("./query-string");
4 | exports.testHashes = require("./hashes");
5 | exports.testIO = require("./io/all-tests");
6 | exports.testOS = require("./os/all-tests");
7 | exports.testFile = require("./file/all-tests");
8 | exports.testUtil = require("./util/all-tests");
9 | exports.testArgs = require("./args");
10 | exports.testEvents = require("./events");
11 |
12 | exports.testGlobal = require("./global");
13 |
14 | exports.testCommonjs = require("./commonjs/all-tests");
15 |
16 | if (require.main == module)
17 | require("os").exit(require("test/runner").run(exports));
18 |
19 |
--------------------------------------------------------------------------------
/tests/args.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('util');
3 | var args = require('args');
4 | var assert = require('test/assert');
5 |
6 | // subclass Parser to prevent it from assertively
7 | // exiting the test suite
8 | var Parser = exports.Parser = function () {
9 | args.Parser.apply(this, arguments);
10 | };
11 | Parser.prototype = Object.create(args.Parser.prototype);
12 | Parser.prototype.constructor = Parser;
13 | Parser.prototype.exit = function () {
14 | throw new Exit();
15 | };
16 | Parser.prototype.print = function () {
17 | if (system.debug)
18 | args.Parser.prototype.print.apply(this, arguments);
19 | };
20 | var Exit = exports.Exit = function () {
21 | Error.apply(this, arguments);
22 | };
23 | Exit.prototype = Object.create(Error.prototype);
24 |
25 | exports.testOptions = require("./args/options");
26 | exports.testDomain = require("./args/domain");
27 | exports.testShifting = require("./args/shifting");
28 | exports.testChoices = require("./args/choices");
29 |
30 | if (require.main == module.id)
31 | require("os").exit(require("test/runner").run(exports));
32 |
33 |
--------------------------------------------------------------------------------
/tests/args/choices.js:
--------------------------------------------------------------------------------
1 |
2 | var ASSERT = require("assert");
3 | var ARGS = require("../args");
4 |
5 | exports.testChoicesArray = function () {
6 |
7 | var parser = new ARGS.Parser();
8 |
9 | parser.option('--bundle-type', 'bundleType')
10 | .help("type of bundle to be built")
11 | .def('xo')
12 | .choices(['xo', 'web'])
13 | .set();
14 |
15 | parser.parse(['command', '--bundle-type', 'xo']);
16 |
17 | };
18 |
19 | if (require.main == module.id)
20 | require("os").exit(require("test").run(exports));
21 |
22 |
--------------------------------------------------------------------------------
/tests/args/options.js:
--------------------------------------------------------------------------------
1 | var args = require('args');
2 | var assert = require("test/assert");
3 | var test = require("../args");
4 |
5 | exports.testBasis = function () {
6 | var parser = new test.Parser();
7 | var options = parser.parse([]);
8 | assert.eq(["args"], Object.keys(options));
9 | };
10 |
11 | exports.testShortOptionSetUnnamed = function () {
12 | var parser = new test.Parser();
13 | parser.option('-o').set();
14 | var options = parser.parse(['c', '-o', 'a']);
15 | assert.eq("a", options.o);
16 | assert.eq(["args", "command", "o"], Object.keys(options));
17 | };
18 |
19 | exports.testLongOptionSetUnnamed = function () {
20 | var parser = new test.Parser();
21 | parser.option('-o', '--option').set();
22 | var options = parser.parse(['c', '--option', 'a']);
23 | assert.eq("a", options.option);
24 | assert.eq(["args", "command", "option"], Object.keys(options));
25 | };
26 |
27 | exports.testLongOptionSet = function () {
28 | var parser = new test.Parser();
29 | parser.option('-o', '--option', 'option').set();
30 | var options = parser.parse(['c', '--option', 'a']);
31 | assert.eq("a", options.option);
32 | assert.eq(["args", "command", "option"], Object.keys(options));
33 | };
34 |
35 | if (require.main == module.id)
36 | require("os").exit(require("test/runner").run(exports));
37 |
--------------------------------------------------------------------------------
/tests/args/shifting.js:
--------------------------------------------------------------------------------
1 |
2 | var args = require('args');
3 | var assert = require("test/assert");
4 | var test = require("../args");
5 |
6 | function Parser() {
7 | var parser = new test.Parser();
8 | parser.option('-s', '--set').set();
9 | parser.option('-f', '--flag').set(true);
10 | parser.option('-2', '--two')
11 | .action(function (options, name, a, b) {
12 | options[name] = [a, b];
13 | });
14 | return parser;
15 | };
16 |
17 | exports.testSetShort = function () {
18 | var parser = Parser();
19 | var options = parser.parse(['command', '-s', 'value']);
20 | assert.eq('value', options.set);
21 | assert.eq([], options.args);
22 | };
23 |
24 | exports.testSetShortMerged = function () {
25 | var parser = Parser();
26 | var options = parser.parse(['command', '-svalue']);
27 | assert.eq('value', options.set);
28 | assert.eq([], options.args);
29 | };
30 |
31 | exports.testFlagSetShortMerged = function () {
32 | var parser = Parser();
33 | var options = parser.parse(['command', '-fsvalue']);
34 | assert.eq(true, options.flag);
35 | assert.eq('value', options.set);
36 | assert.eq([], options.args);
37 | };
38 |
39 | exports.testFlagSetShortMergedRemainder = function () {
40 | var parser = Parser();
41 | var options = parser.parse(['command', '-fsvalue', 'hi']);
42 | assert.eq('command', options.command);
43 | assert.eq(true, options.flag);
44 | assert.eq('value', options.set);
45 | assert.eq(['hi'], options.args);
46 | };
47 |
48 | exports.testTwoShort = function () {
49 | var parser = Parser();
50 | var options = parser.parse(['command', '-2', 'a', 'b', 'c']);
51 | assert.eq(['a', 'b'], options.two);
52 | assert.eq(['c'], options.args);
53 | };
54 |
55 | exports.testTwoShortMerged = function () {
56 | var parser = Parser();
57 | var options = parser.parse(['command', '-2a', 'b', 'c']);
58 | assert.eq(['a', 'b'], options.two);
59 | assert.eq(['c'], options.args);
60 | };
61 |
62 | exports.testSetLong = function () {
63 | var parser = Parser();
64 | var options = parser.parse(['command', '--set', 'value']);
65 | assert.eq('value', options.set);
66 | assert.eq([], options.args);
67 | };
68 |
69 | exports.testSetLongMerged = function () {
70 | var parser = Parser();
71 | var options = parser.parse(['command', '--set=value']);
72 | assert.eq('value', options.set);
73 | assert.eq([], options.args);
74 | };
75 |
76 | exports.testHaltOptions = function () {
77 | var parser = Parser();
78 | var options = parser.parse(['command', '--', '-svalue']);
79 | assert.eq(undefined, options.set);
80 | assert.eq(['-svalue'], options.args);
81 | };
82 |
83 | exports.testNoSuchOption = function () {
84 | var parser = Parser();
85 | assert.throwsError(function () {
86 | parser.parse(['command', '--no-such-option']);
87 | }, test.Exit)
88 | };
89 |
90 | if (require.main == module.id)
91 | require("os").exit(require("test/runner").run(exports));
92 |
93 |
--------------------------------------------------------------------------------
/tests/args/validation.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('util');
3 | var args = require('args');
4 | var assert = require('test/assert');
5 | var test = require('../args');
6 |
7 | exports.testValidateMultiple = function () {
8 | var parser = new test.Parser();
9 | parser.option('-o')
10 | .action(function (options, name, value) {
11 | })
12 | .validate(function (value) {
13 | })
14 | };
15 |
16 | exports.testValidatorChain = function () {
17 | var parser = new test.Parser();
18 | parser.option('-o')
19 | .action(function (options, name, value) {
20 | })
21 | .validate(function (value) {
22 | return value;
23 | })
24 | .validate(function (value) {
25 | return value;
26 | })
27 | };
28 |
29 | if (require.main == module.id)
30 | require("os").exit(require("test/runner").run(exports));
31 |
32 |
--------------------------------------------------------------------------------
/tests/base64.js:
--------------------------------------------------------------------------------
1 |
2 | var base64 = require('base64.js');
3 | var binary = require('binary');
4 | var assert = require('test/assert.js');
5 |
6 | var raw = "Once upon a time, in a far away land.\n";
7 | var encoded = 'T25jZSB1cG9uIGEgdGltZSwgaW4gYSBmYXIgYXdheSBsYW5kLgo=';
8 |
9 | exports.testEncode = function () {
10 | assert.eq(base64.encode(raw), encoded, 'encoded');
11 | };
12 |
13 | exports.testDecode = function () {
14 | assert.eq(base64.decode(encoded), raw, 'decoded');
15 | };
16 |
17 | exports.testEncodeDecode = function () {
18 | assert.eq(base64.decode(base64.encode(raw)), raw, 'encode decode identity');
19 | };
20 |
21 | if (require.main == module.id)
22 | require("os").exit(require("test/runner").run(exports));
23 |
24 |
--------------------------------------------------------------------------------
/tests/commonjs.js:
--------------------------------------------------------------------------------
1 | exports.testCommonjs = require("./commonjs/all-tests");
2 | if (require.main == module.id)
3 | require("os").exit(require("test/runner").run(exports));
4 |
--------------------------------------------------------------------------------
/tests/commonjs/all-tests.js:
--------------------------------------------------------------------------------
1 | exports.testModules = require("./modules/all-tests");
2 | exports.testModulesUTF8 = require("./module-tests");
3 | exports.testAssert = require("./assert");
4 | exports.testByteArray = require("./bytearray-tests");
5 | exports.testByteString = require("./bytestring-tests");
6 | exports.testByteArrayEncodings = require("./bytearray-encodings-tests");
7 | exports.testByteStringEncodings = require("./bytestring-encodings-tests");
8 | exports.testFile = require("./file-tests");
9 | exports.testEs5 = require("./es5/all-tests");
10 |
11 | if (require.main == module.id)
12 | require("os").exit(require("test/runner").run(exports));
13 |
--------------------------------------------------------------------------------
/tests/commonjs/bytearray-encodings-tests.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 |
3 | var Binary = require("binary").Binary,
4 | ByteString = require("binary").ByteString,
5 | ByteArray = require("binary").ByteArray;
6 |
7 | exports.testByteArrayConstructorEncodings = function() {
8 | // ByteString(string, charset)
9 | // Convert a string. The ByteString will contain string encoded with charset.
10 | var testString = "hello world";
11 | var b = new ByteArray(testString, "US-ASCII");
12 | assert.isEqual(testString.length, b.length);
13 | b.length = 678;
14 | assert.isEqual(678, b.length);
15 | assert.isEqual(testString.charCodeAt(0), b.get(0));
16 | assert.isEqual(testString.charCodeAt(testString.length-1), b.get(testString.length-1));
17 | assert.isEqual(0, b.get(677));
18 | };
19 |
20 | exports.testToByteArrayEncodings = function() {
21 | var testString = "I ♥ JS";
22 | assert.isEqual(testString, new ByteArray(testString, "UTF-8").toByteArray("UTF-8", "UTF-16").decodeToString("UTF-16"));
23 | };
24 |
25 | exports.testToByteStringEncodings = function() {
26 | var testString = "I ♥ JS";
27 | assert.isEqual(testString, new ByteArray(testString, "UTF-8").toByteString("UTF-8", "UTF-16").decodeToString("UTF-16"));
28 | };
29 |
30 | exports.testToArrayEncodings = function() {
31 | var a1;
32 |
33 | a1 = new ByteArray("\u0024\u00A2\u20AC", "UTF-8").toArray("UTF-8");
34 | assert.isEqual(3, a1.length);
35 | assert.isEqual(0x24, a1[0]);
36 | assert.isEqual(0xA2, a1[1]);
37 | assert.isEqual(0x20AC, a1[2]);
38 |
39 | a1 = new ByteArray("\u0024\u00A2\u20AC", "UTF-16").toArray("UTF-16");
40 | assert.isEqual(3, a1.length);
41 | assert.isEqual(0x24, a1[0]);
42 | assert.isEqual(0xA2, a1[1]);
43 | assert.isEqual(0x20AC, a1[2]);
44 | };
45 |
46 | exports.testDecodeToString = function() {
47 | assert.isEqual("hello world", new ByteArray("hello world", "US-ASCII").decodeToString("US-ASCII"));
48 |
49 | assert.isEqual("I ♥ JS", new ByteArray("I ♥ JS", "UTF-8").decodeToString("UTF-8"));
50 |
51 | assert.isEqual("\u0024", new ByteArray([0x24]).decodeToString("UTF-8"));
52 | assert.isEqual("\u00A2", new ByteArray([0xC2,0xA2]).decodeToString("UTF-8"));
53 | assert.isEqual("\u20AC", new ByteArray([0xE2,0x82,0xAC]).decodeToString("UTF-8"));
54 | // FIXME:
55 | //assert.isEqual("\u10ABCD", (new ByteArray([0xF4,0x8A,0xAF,0x8D])).decodeToString("UTF-8"));
56 |
57 | assert.isEqual("\u0024", new ByteArray("\u0024", "UTF-8").decodeToString("UTF-8"));
58 | assert.isEqual("\u00A2", new ByteArray("\u00A2", "UTF-8").decodeToString("UTF-8"));
59 | assert.isEqual("\u20AC", new ByteArray("\u20AC", "UTF-8").decodeToString("UTF-8"));
60 | assert.isEqual("\u10ABCD", new ByteArray("\u10ABCD", "UTF-8").decodeToString("UTF-8"));
61 |
62 | assert.isEqual("\u0024", new ByteArray("\u0024", "UTF-16").decodeToString("UTF-16"));
63 | assert.isEqual("\u00A2", new ByteArray("\u00A2", "UTF-16").decodeToString("UTF-16"));
64 | assert.isEqual("\u20AC", new ByteArray("\u20AC", "UTF-16").decodeToString("UTF-16"));
65 | assert.isEqual("\u10ABCD", new ByteArray("\u10ABCD", "UTF-16").decodeToString("UTF-16"));
66 | };
67 |
68 | if (require.main == module.id)
69 | require("os").exit(require("test/runner").run(exports));
70 |
--------------------------------------------------------------------------------
/tests/commonjs/es5/all-tests.js:
--------------------------------------------------------------------------------
1 | exports.testFunctionBind = require("./bind");
2 | if (require.main == module)
3 | require("os").exit(require("test").run(exports));
4 |
--------------------------------------------------------------------------------
/tests/commonjs/es5/bind.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("assert");
3 |
4 | exports.testThis = function () {
5 | var foo = function (y) {
6 | return this.x + y;
7 | };
8 | assert.equal(20, foo.bind({x:10})(10));
9 | };
10 |
11 | exports.testPartial = function () {
12 | var foo = function (y) {
13 | return this.x + y;
14 | };
15 | assert.equal(20, foo.bind({x:10}, 10)());
16 | };
17 |
18 | /* XXX disputed
19 | exports.testConstructor = function () {
20 | var Foo = function (x, y) {
21 | this.a = x + y;
22 | };
23 | assert.equal(30, new (Foo.bind())(10, 20).a);
24 | assert.equal(30, new (Foo.bind(10))(20).a);
25 | assert.equal(30, new (Foo.bind(10, 20))().a);
26 | };
27 | */
28 |
29 | if (require.main == module)
30 | require("os").exit(require("test").run(exports));
31 |
32 |
--------------------------------------------------------------------------------
/tests/commonjs/es5/date-regression.js:
--------------------------------------------------------------------------------
1 |
2 | exports.testDate = function (ASSERT) {
3 | ASSERT.equal(new Date(1970, 0, 1), "Thu Jan 01 1970 00:00:00 GMT-0800 (PST)");
4 | };
5 |
6 |
--------------------------------------------------------------------------------
/tests/commonjs/file/dirname.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('util');
3 | var assert = require('test/assert');
4 | var fs = require('file');
5 |
6 | util.forEachApply([
7 | // relative
8 | ['', '.'],
9 | ['.', '.'],
10 | ['foo', '.'],
11 | ['foo/', '.'],
12 | ['foo/bar', 'foo'],
13 | ['foo/bar/', 'foo'],
14 | // absolute
15 | ["/", "/"],
16 | ["/foo", "/"],
17 | ["/foo/", "/"],
18 | ["/foo/bar", "/foo"],
19 | ["/foo/bar/", "/foo"]
20 | // TODO: many more tests
21 | // TODO: Windows tests
22 | ], function (path, expected) {
23 | exports['test ' + util.repr(path)] = function () {
24 | var actual = fs.dirname(path);
25 | assert.eq(expected, actual, util.repr(path));
26 | };
27 | });
28 |
29 | if (require.main == module.id)
30 | require("os").exit(require("test/runner").run(exports));
31 |
32 |
--------------------------------------------------------------------------------
/tests/commonjs/file/extension.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('util');
3 | var assert = require('test/assert');
4 | var fs = require('file');
5 |
6 | util.forEachApply([
7 | ['', ''],
8 | ['.', ''],
9 | ['..', ''],
10 | ['.a', ''],
11 | ['..a', ''],
12 | ['.a.b', '.b'],
13 | ['a.b', '.b'],
14 | ['a.b.c', '.c'],
15 | ['/', ''],
16 | ['/.', ''],
17 | ['/..', ''],
18 | ['/..a', ''],
19 | ['/.a.b', '.b'],
20 | ['/a.b', '.b'],
21 | ['/a.b.c', '.c'],
22 | ['foo/', ''],
23 | ['foo/.', ''],
24 | ['foo/..', ''],
25 | ['foo/..a', ''],
26 | ['foo/.a.b', '.b'],
27 | ['foo/a.b', '.b'],
28 | ['foo/a.b.c', '.c'],
29 | ['/foo/', ''],
30 | ['/foo/.', ''],
31 | ['/foo/..', ''],
32 | ['/foo/..a', ''],
33 | ['/foo/.a.b', '.b'],
34 | ['/foo/a.b', '.b'],
35 | ['/foo/a.b.c', '.c']
36 | ], function (path, expected) {
37 | exports['test ' + util.repr(path)] = function () {
38 | var actual = fs.extension(path);
39 | assert.eq(expected, actual, util.repr(path));
40 | };
41 | });
42 |
43 | if (require.main == module.id)
44 | require("os").exit(require("test/runner").run(exports));
45 |
46 |
--------------------------------------------------------------------------------
/tests/commonjs/file/is-absolute.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require('test/assert');
3 | var fs = require('file');
4 |
5 | exports.testIsAbsolute = function () {
6 | assert.eq(true, fs.isAbsolute(fs.absolute(module.path)), 'absolute module path is absolute');
7 | };
8 |
9 | if (require.main == module.id)
10 | require("os").exit(require("test/runner").run(exports));
11 |
12 |
--------------------------------------------------------------------------------
/tests/commonjs/file/iterator.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var fs = require("file");
4 |
5 | /* a decorator that passes a path object corresponding
6 | to the test name and removes any files created
7 | therein afterward */
8 | var Test = function (block) {
9 | var args = arguments;
10 | var exported = function () {
11 | for (var name in exports) {
12 | if (exports[name] === exported) {
13 | try {
14 | var path = fs.path(
15 | fs.resolve(module.path, '.'),
16 | name
17 | );
18 | block(path);
19 | } finally {
20 | if (path.exists())
21 | path.rmtree();
22 | }
23 | }
24 | }
25 | };
26 | return exported;
27 | };
28 |
29 | exports.testPrintReadLine = Test(function (path) {
30 | var stream = path.open('w');
31 | stream.print('hello');
32 | stream.print('world');
33 | stream.close();
34 | stream = path.open('r');
35 | assert.is('hello\n', stream.readLine());
36 | assert.is('world\n', stream.readLine());
37 | assert.is('', stream.readLine());
38 | });
39 |
40 | exports.testPrintReadLineChain = Test(function (path) {
41 | var stream = path.open('w');
42 | stream.print('hello').print('world');
43 | stream.close();
44 | stream = path.open('r');
45 | assert.is('hello\n', stream.readLine());
46 | assert.is('world\n', stream.readLine());
47 | assert.is('', stream.readLine());
48 | });
49 |
50 | exports.testReadLines = Test(function (path) {
51 | var stream = path.open('w');
52 | stream.print('hello').print('world');
53 | stream.close();
54 | stream = path.open('r');
55 | assert.eq(['hello\n', 'world\n'], stream.readLines());
56 | });
57 |
58 | exports.testForEach = Test(function (path) {
59 | var output = path.open('w');
60 | var input = path.open('r');
61 | output.print('1');
62 | output.print('1');
63 | var count = 0;
64 | input.forEach(function (line) {
65 | assert.eq('1', line);
66 | count++;
67 | });
68 | assert.eq(2, count);
69 | output.print('2').print('2');
70 | input.forEach(function (line) {
71 | assert.eq('2', line);
72 | count++;
73 | });
74 | assert.eq(4, count);
75 | output.close();
76 | input.close();
77 | });
78 |
79 | exports.testNext = Test(function (path) {
80 | path.open('w').print('1').print('2').close();
81 | var iterator = path.open();
82 | assert.is('1', iterator.next());
83 | assert.is('2', iterator.next());
84 | assert.throwsError(function () {
85 | iterator.next();
86 | });
87 | });
88 |
89 | exports.testIterator = Test(function (path) {
90 | path.open('w').print('1').print('2').close();
91 | var iterator = path.open().iterator();
92 | assert.is('1', iterator.next());
93 | assert.is('2', iterator.next());
94 | assert.throwsError(function () {
95 | iterator.next();
96 | });
97 | });
98 |
99 | if (require.main == module.id)
100 | require("os").exit(require("test/runner").run(exports));
101 |
102 |
--------------------------------------------------------------------------------
/tests/commonjs/file/normal.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('util');
3 | var assert = require('test/assert');
4 | var fs = require('file');
5 |
6 | util.forEachApply([
7 | ['', ''],
8 | ['.', ''],
9 | ['./', ''],
10 | ['../', '../'],
11 | ['../a', '../a'],
12 | ['../a/', '../a/'],
13 | ['a/..', ''],
14 | ['a/../', ''],
15 | ['a/../b', 'b'],
16 | ['a/../b/', 'b/'],
17 | ], function (path, expected) {
18 | exports['test ' + util.repr(path)] = function () {
19 | var result = '';
20 | var actual = fs.normal(path);
21 | assert.eq(expected, actual, util.repr(path));
22 | };
23 | });
24 |
25 | if (require.main == module.id)
26 | require("os").exit(require("test/runner").run(exports));
27 |
28 |
--------------------------------------------------------------------------------
/tests/commonjs/file/path.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var file = require("file");
4 | var util = require("util");
5 |
6 | util.forEachApply([
7 | ["/", "a", "/a"],
8 | [".", "a", "./a"]
9 | ], function (path, rel, expected) {
10 | exports['test path.join ' + util.repr(arguments)] = function () {
11 | assert.eq(expected, system.fs.path(path).join(rel));
12 | };
13 | });
14 |
15 | if (require.main === module.id)
16 | require("os").exit(require("test/runner").run(exports));
17 |
18 |
--------------------------------------------------------------------------------
/tests/commonjs/file/relative.js:
--------------------------------------------------------------------------------
1 |
2 | var system = require('system');
3 | var util = require('util');
4 | var assert = require('test/assert');
5 | var fs = require('file');
6 |
7 | util.forEachApply([
8 | ['', '', ''],
9 | ['.', '', ''],
10 | ['', '.', ''],
11 | ['.', '.', ''],
12 | ['', '..', '../'],
13 | ['', '../', '../'],
14 | ['a', 'b', 'b'],
15 | ['../a', '../b', 'b'],
16 | ['../a/b', '../a/c', 'c'],
17 | ['a/b', '..', '../../'],
18 | ['a/b', 'c', '../c'],
19 | ['a/b', 'c/d', '../c/d'],
20 | // XXX the next two are disputed - kriskowal
21 | ["a", "a/b/c", "b/c"],
22 | ["a/", "a/b/c", "b/c"]
23 |
24 | ], function (source, target, expected) {
25 | var name = (
26 | util.repr(source) + ' -> ' + util.repr(target) +
27 | ' = ' + util.repr(expected)
28 | );
29 | exports['test ' + name] = function () {
30 | var result = '';
31 | var actual = fs.relative(source, target);
32 | assert.eq(
33 | expected,
34 | actual,
35 | name
36 | );
37 | };
38 | });
39 |
40 | if (require.main == module.id)
41 | require("os").exit(require("test/runner").run(exports));
42 |
43 |
--------------------------------------------------------------------------------
/tests/commonjs/file/resolve.js:
--------------------------------------------------------------------------------
1 |
2 | var system = require('system');
3 | var util = require('util');
4 | var assert = require('test/assert');
5 | var fs = require('file');
6 |
7 | util.forEachApply([
8 | [['/'], '/'],
9 | [['/a'], '/a'],
10 | [['/a/'], '/a/'],
11 | [['/a', '/b'], '/b'],
12 | [['/a', '/b/'], '/b/'],
13 | [['/', 'a'], '/a'],
14 | [['/', 'a/'], '/a/'],
15 | [['/a', 'a'], '/a'],
16 | [['/a', 'a/'], '/a/'],
17 | [['/a/', 'a'], '/a/a'],
18 | [['/a/', 'a/'], '/a/a/'],
19 | [['..'], '../'],
20 | [['..', 'a'], '../a'],
21 | [['..', 'a/'], '../a/'],
22 | [['.'], ''],
23 | [['.', 'a'], 'a'],
24 | [['.', 'a/'], 'a/'],
25 | [['a', '.'], ''],
26 | [['a', '.', 'a'], 'a'],
27 | [['a', '.', 'a/'], 'a/'],
28 | [['a', '..'], '../'],
29 | [['a', '..', 'a'], '../a'],
30 | [['a', '..', 'a/'], '../a/'],
31 | [['a/', '..'], ''],
32 | [['a/', '..', 'a'], 'a'],
33 | [['a/', '..', 'a/'], 'a/'],
34 | [['a/b', ''], 'a/b'],
35 | ], function (parts, expected) {
36 | exports['test ' + util.repr(parts)] = function () {
37 | var result = '';
38 | var actual = fs.resolve.apply(null, parts);
39 | assert.eq(expected, actual, util.repr(parts));
40 | };
41 | });
42 |
43 | if (require.main == module.id)
44 | require("os").exit(require("test/runner").run(exports));
45 |
--------------------------------------------------------------------------------
/tests/commonjs/fs-base.js:
--------------------------------------------------------------------------------
1 |
2 | var ASSERT = require("assert");
3 | var FS;
4 |
5 | exports.testInitialize = function () {
6 | FS = require("fs-base");
7 | };
8 |
9 | exports.testExists = function () {
10 | ASSERT.ok(FS.exists(module.path));
11 | };
12 |
13 | exports.testIsFile = function () {
14 | ASSERT.ok(FS.isFile(module.path));
15 | };
16 |
17 | exports.testSame = function () {
18 | ASSERT.ok(FS.same(module.path, module.path));
19 | };
20 |
21 | if (require.main == module)
22 | require("os").exit(require("test").run(exports));
23 |
24 |
--------------------------------------------------------------------------------
/tests/commonjs/module-tests.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 |
3 | exports.testModuleCharsetIsUtf8 = function () {
4 | assert.isEqual(
5 | 1, "♥".length,
6 | 'unicode characters should have length of 1'
7 | );
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/absolute/b.js:
--------------------------------------------------------------------------------
1 | exports.foo = function() {};
2 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/absolute/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | var a = require('submodule/a');
3 | var b = require('b');
4 | test.assert(a.foo().foo === b.foo, 'require works with absolute identifiers');
5 | print('DONE', 'info');
6 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/absolute/submodule/a.js:
--------------------------------------------------------------------------------
1 | exports.foo = function () {
2 | return require('b');
3 | };
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/absolute/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/all-tests.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 |
3 | var assert = require('test/assert');
4 | var sandbox = require('sandbox').sandbox;
5 | var fs = require('file');
6 |
7 | [
8 | 'absolute',
9 | 'cyclic',
10 | 'exactExports',
11 | 'hasOwnProperty',
12 | 'method',
13 | 'missing',
14 | 'monkeys',
15 | 'nested',
16 | 'relative',
17 | 'transitive',
18 | 'determinism'
19 | ].forEach(function (testName) {
20 | exports['test ' + testName] = function () {
21 | var prefix = fs.path(module.id).resolve(testName).join('');
22 | var done;
23 |
24 | var print = function (message) {
25 | assert.isFalse(/^FAIL/.test(message));
26 | if (/^ERROR/.test(message))
27 | throw new Error(message);
28 | if (/^DONE/.test(message))
29 | done = true;
30 | };
31 |
32 | sandbox(
33 | 'program',
34 | system,
35 | {
36 | prefix: prefix,
37 | loader: require.loader,
38 | print: print
39 | }
40 | );
41 | assert.isTrue(done, 'done');
42 | };
43 | });
44 |
45 | if (module.id == require.main)
46 | require('os').exit(require('test/runner').run(exports));
47 |
48 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/config.js:
--------------------------------------------------------------------------------
1 | (function (env) {
2 | try {
3 | var sandbox = require('chiron/sandbox').sandbox;
4 | var base = require('chiron/base');
5 | var log = base.List();
6 | sandbox('test/iojs/program', {print: log.push});
7 | return [200, {'Content-type': 'text/plain'}, log.eachIter(base.add("\n"))];
8 | } catch (exception) {
9 | return [500, {'Content-type': 'text/plain'}, [''+(exception.message || exception)]];
10 | }
11 | });
12 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/cyclic/a.js:
--------------------------------------------------------------------------------
1 | exports.a = function () {
2 | return b;
3 | };
4 | var b = require('b');
5 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/cyclic/b.js:
--------------------------------------------------------------------------------
1 | var a = require('a');
2 | exports.b = function () {
3 | return a;
4 | };
5 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/cyclic/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | var a = require('a');
3 | var b = require('b');
4 |
5 | test.assert(a.a, 'a exists');
6 | test.assert(b.b, 'b exists')
7 | test.assert(a.a().b === b.b, 'a gets b');
8 | test.assert(b.b().a === a.a, 'b gets a');
9 |
10 | print('DONE', 'info');
11 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/cyclic/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/determinism/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | require('submodule/a');
3 | print('DONE', 'info');
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/determinism/submodule/a.js:
--------------------------------------------------------------------------------
1 | var pass = false;
2 | var test = require('test');
3 | try {
4 | require('a');
5 | } catch (exception) {
6 | pass = true;
7 | }
8 | test.assert(pass, 'require does not fall back to relative modules when absolutes are not available.')
9 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/determinism/submodule/b.js:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/determinism/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/exactExports/a.js:
--------------------------------------------------------------------------------
1 | exports.program = function () {
2 | return require('program');
3 | };
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/exactExports/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | var a = require('a');
3 | test.assert(a.program() === exports, 'exact exports');
4 | print('DONE', 'info');
5 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/exactExports/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/hasOwnProperty/hasOwnProperty.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/tests/commonjs/modules/hasOwnProperty/hasOwnProperty.js
--------------------------------------------------------------------------------
/tests/commonjs/modules/hasOwnProperty/program.js:
--------------------------------------------------------------------------------
1 | var hasOwnProperty = require('hasOwnProperty');
2 | var toString = require('toString');
3 | print('DONE', 'info');
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/hasOwnProperty/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/hasOwnProperty/toString.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/tests/commonjs/modules/hasOwnProperty/toString.js
--------------------------------------------------------------------------------
/tests/commonjs/modules/method/a.js:
--------------------------------------------------------------------------------
1 | exports.foo = function () {
2 | return this;
3 | };
4 | exports.set = function (x) {
5 | this.x = x;
6 | };
7 | exports.get = function () {
8 | return this.x;
9 | };
10 | exports.getClosed = function () {
11 | return exports.x;
12 | };
13 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/method/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | var a = require('a');
3 | var foo = a.foo;
4 | test.assert(a.foo() == a, 'calling a module member');
5 | test.assert(foo() == (function (){return this})(), 'members not implicitly bound');
6 | a.set(10);
7 | test.assert(a.get() == 10, 'get and set')
8 | print('DONE', 'info');
9 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/method/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/missing/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | try {
3 | require('bogus');
4 | print('FAIL require throws error when module missing', 'fail');
5 | } catch (exception) {
6 | print('PASS require throws error when module missing', 'pass');
7 | }
8 | print('DONE', 'info');
9 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/missing/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/monkeys/a.js:
--------------------------------------------------------------------------------
1 | require('program').monkey = 10;
2 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/monkeys/program.js:
--------------------------------------------------------------------------------
1 | var a = require('a');
2 | var test = require('test');
3 | test.assert(exports.monkey == 10, 'monkeys permitted');
4 | print('DONE', 'info');
5 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/monkeys/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/nested/a/b/c/d.js:
--------------------------------------------------------------------------------
1 | exports.foo = function () {
2 | return 1;
3 | };
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/nested/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | test.assert(require('a/b/c/d').foo() == 1, 'nested module identifier');
3 | print('DONE', 'info');
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/nested/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/relative/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | var a = require('submodule/a');
3 | var b = require('submodule/b');
4 | test.assert(a.foo == b.foo, 'a and b share foo through a relative require');
5 | print('DONE', 'info');
6 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/relative/submodule/a.js:
--------------------------------------------------------------------------------
1 | exports.foo = require('./b').foo;
2 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/relative/submodule/b.js:
--------------------------------------------------------------------------------
1 | exports.foo = function () {
2 | };
3 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/relative/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/transitive/a.js:
--------------------------------------------------------------------------------
1 | exports.foo = require('b').foo;
2 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/transitive/b.js:
--------------------------------------------------------------------------------
1 | exports.foo = require('c').foo;
2 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/transitive/c.js:
--------------------------------------------------------------------------------
1 | exports.foo = function () {
2 | return 1;
3 | };
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/transitive/program.js:
--------------------------------------------------------------------------------
1 | var test = require('test');
2 | test.assert(require('a').foo() == 1, 'transitive');
3 | print('DONE', 'info');
4 |
--------------------------------------------------------------------------------
/tests/commonjs/modules/transitive/test.js:
--------------------------------------------------------------------------------
1 |
2 | exports.assert = function (guard, message) {
3 | if (guard) {
4 | print('PASS ' + message, 'pass');
5 | } else {
6 | print('FAIL ' + message, 'fail');
7 | }
8 | };
9 |
10 |
--------------------------------------------------------------------------------
/tests/file/all-tests.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var fs = require("file");
3 |
4 | exports.testIsLink = function () {
5 |
6 | var here = fs.path(module.path).dirname().join("_test");
7 | if (here.exists()) {
8 | here.rmtree();
9 | }
10 | here.mkdirs();
11 | try {
12 | var dir1 = here.join("dir1");
13 | dir1.mkdirs();
14 | var dir2 = here.join("dir2");
15 | dir2.mkdirs();
16 | dir2.join("file2").touch();
17 |
18 | dir2.symlink(dir1.join("linkToDir2"));
19 |
20 | assert.isFalse(dir2.isLink());
21 | assert.isTrue(dir1.join("linkToDir2").isLink());
22 |
23 | dir2.join("file2").symlink(dir1.join("linkToFile1"));
24 |
25 | assert.isFalse(dir2.join("file2").isLink());
26 | assert.isTrue(dir1.join("linkToFile1").isLink());
27 | } finally {
28 | here.rmtree();
29 | }
30 | }
31 |
32 | exports.testRmtreeDoesNotFollowSymlinks = function () {
33 | var here = fs.path(module.path).dirname().join("_test");
34 | if (here.exists()) {
35 | here.rmtree();
36 | }
37 | here.mkdirs();
38 | try {
39 | var dir1 = here.join("dir1");
40 | dir1.mkdirs();
41 | var dir2 = here.join("dir2");
42 | dir2.mkdirs();
43 | dir2.symlink(dir1.join("linkToDir2"));
44 | dir2.join("file2").touch();
45 |
46 | dir1.rmtree();
47 |
48 | assert.isFalse(dir1.exists());
49 | assert.isTrue(dir2.exists());
50 | assert.isTrue(dir2.join("file2").exists());
51 | } finally {
52 | here.rmtree();
53 | }
54 | };
55 |
56 | exports.testFileFNMatch = require("./fnmatch");
57 | exports.testFileMatch = require("./match");
58 | exports.testFileMatch = require("./glob");
59 |
60 | if (require.main == module.id)
61 | require("os").exit(require("test/runner").run(exports));
62 |
--------------------------------------------------------------------------------
/tests/global.js:
--------------------------------------------------------------------------------
1 |
2 | exports.testArray = require("./global/array");
3 |
4 | if (require.main == module.id)
5 | require("os").exit(require("test/runner").run(exports));
6 |
7 |
--------------------------------------------------------------------------------
/tests/global/array.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require('test/assert');
3 |
4 | exports.testIsArray = function () {
5 | assert.isTrue(Array.isArray([]));
6 | };
7 |
8 | exports.testIsArrayNegativeArguments = function () {
9 | var args = (function () {return arguments})();
10 | assert.isFalse(Array.isArray(args));
11 | };
12 |
13 | exports.testIsArrayNegativeObject = function () {
14 | assert.isFalse(Array.isArray({"length": 0}));
15 | };
16 |
17 | if (require.main == module.id)
18 | require("os").exit(require("test/runner").run(exports));
19 |
20 |
--------------------------------------------------------------------------------
/tests/global/date-parse.js:
--------------------------------------------------------------------------------
1 |
2 | var UTIL = require("util");
3 | var ASSERT = require("assert");
4 |
5 | [
6 | "2010-01-01T00:00:00.000Z",
7 | ].forEach(function (isoDate) {
8 | exports['testReflexiveParseFormat ' + isoDate] = function () {
9 | var parsed = Date.parse(isoDate);
10 | ASSERT.equal(new Date(parsed).toISOString(), isoDate);
11 | };
12 | });
13 |
14 | UTIL.forEachApply([
15 | ["2010", "2010-01-01T00:00:00.000Z"],
16 | ["2010-01", "2010-01-01T00:00:00.000Z"],
17 | ["2010-01-01", "2010-01-01T00:00:00.000Z"],
18 | ["2010-01-01T00:00Z", "2010-01-01T00:00:00.000Z"],
19 | ["2010-01-01T00:00:00Z", "2010-01-01T00:00:00.000Z"],
20 | ["2010-01-01T00:00:00.000Z", "2010-01-01T00:00:00.000Z"],
21 | ["2010-01-01T00:00:00.000+01:01", "2010-01-01T01:01:00.000Z"], // explicit timezone
22 | /* not really realistic to get these working:
23 | ["0010", "0010-01-01T00:00:00.000Z"], // before 1900
24 | ["0010-01", "0010-01-01T00:00:00.000Z"],
25 | ["0010-01-01", "0010-01-01T00:00:00.000Z"],
26 | ["+100000-01-01T00:00:00.000Z", "+100000-01-01T00:00:00.000Z"],
27 | ["-100000-01-01T00:00:00.000Z", "-100000-01-01T00:00:00.000Z"],
28 | ["+002010-01-01T00:00:00.000Z", "2010-01-01T00:00:00.000Z"]
29 | */
30 | ], function (input, output) {
31 | exports['testNonReflexiveParseFormat ' + input] = function () {
32 | var parsed = Date.parse(input);
33 | ASSERT.equal(new Date(parsed).toISOString(), output);
34 | };
35 | });
36 |
37 | exports.testTimes = function () {
38 | ASSERT.equal(Date.parse("T00:00:00.001"), 1);
39 | ASSERT.equal(Date.parse("T00:00:01.000"), 1000);
40 | ASSERT.equal(Date.parse("T00:01:00.000"), 60000);
41 | ASSERT.equal(Date.parse("T01:00:00.000"), 3600000);
42 | };
43 |
44 | if (require.main == module)
45 | require("test").run(exports);
46 |
47 |
--------------------------------------------------------------------------------
/tests/html.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 |
3 | var html = require("nitro/utils/html"),
4 | escapeHTML = html.escapeHTML,
5 | stripTags = html.stripTags;
6 |
7 | exports.testEscapeHTML = function() {
8 | var str = 'hello
';
9 | assert.isEqual(escapeHTML(str), '<p class="text">hello</p>');
10 | }
11 |
12 | exports.testStripTags = function() {
13 | }
14 |
--------------------------------------------------------------------------------
/tests/interpreter.js:
--------------------------------------------------------------------------------
1 | var ASSERT = require("test/assert");
2 |
3 | var Context = require("interpreter").Context;
4 |
5 | exports.testContextGlobalAssignment = function() {
6 | var c = new Context();
7 |
8 | ASSERT.isTrue(typeof global.foo === "undefined");
9 | ASSERT.isTrue(!c.global.foo);
10 |
11 | var testObj = {};
12 |
13 | c.global.foo = testObj;
14 |
15 | ASSERT.isTrue(typeof global.foo === "undefined");
16 | ASSERT.eq(testObj, c.global.foo);
17 | ASSERT.eq(testObj, c.eval("foo"));
18 | ASSERT.eq(testObj, (new c.Function("return foo;"))());
19 | }
20 |
21 | exports.testContextEval = function() {
22 | var c = new Context();
23 |
24 | ASSERT.isTrue(typeof global.foo === "undefined");
25 | ASSERT.isTrue(!c.global.foo);
26 |
27 | c.eval("foo = 1234;");
28 |
29 | ASSERT.isTrue(typeof global.foo === "undefined");
30 | ASSERT.eq(1234, c.global.foo);
31 | ASSERT.eq(1234, c.eval("foo"));
32 | ASSERT.eq(1234, (new c.Function("return foo;"))());
33 | }
34 |
35 | exports.testContextFunction = function() {
36 | var c = new Context();
37 |
38 | ASSERT.isTrue(typeof global.foo === "undefined");
39 | ASSERT.isTrue(!c.global.foo);
40 |
41 | var testObj = {};
42 |
43 | (new c.Function("bar", "foo = bar;"))(testObj);
44 |
45 | ASSERT.isTrue(typeof global.foo === "undefined");
46 | ASSERT.eq(testObj, c.global.foo);
47 | ASSERT.eq(testObj, c.eval("foo"));
48 | ASSERT.eq(testObj, (new c.Function("return foo;"))());
49 | }
50 |
51 | exports.testContextGlobal = function() {
52 | var c = new Context();
53 |
54 | ASSERT.eq(c.eval("(function(){ return this; })()"), c.global);
55 |
56 | ASSERT.eq(c.eval("this"), c.global);
57 |
58 | ASSERT.isTrue(c.eval("(function(){ return this; })() === this"));
59 |
60 | ASSERT.isTrue(global !== c.global, "Context global should be unique.");
61 | }
62 |
63 | exports.testContextPrimordials = function() {
64 | var c = new Context();
65 |
66 | var globalNames = [
67 | "Array", "Boolean", "Date", "Error", "EvalError", "Function",
68 | "Math", "Number", "Object", "RangeError", "ReferenceError",
69 | "RegExp", "String", "SyntaxError", "TypeError", "URIError",
70 | "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent",
71 | "eval", "isFinite", "isNaN", "parseFloat", "parseInt",
72 | ];
73 |
74 | globalNames.forEach(function(globalName) {
75 | ASSERT.isTrue(!!c.global[globalName], globalName + " global should exist");
76 | ASSERT.isTrue(c.global[globalName] !== global[globalName], globalName + " global should be different than parent Context's");
77 | });
78 | }
79 |
80 | if (require.main == module)
81 | require("os").exit(require("test/runner").run(exports));
82 |
--------------------------------------------------------------------------------
/tests/io/all-tests.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 |
3 | exports.testTextInputStream = require("./textinputstream");
4 |
5 |
6 | if (require.main === module.id)
7 | require("os").exit(require("test/runner").run(exports));
--------------------------------------------------------------------------------
/tests/io/stringio.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var io = require("io");
4 |
5 | exports.testStringIODelimiter = function () {
6 | var stringio = new io.StringIO("a\0b\0", "\0");
7 | assert.eq(["a\0", "b\0"], stringio.readLines());
8 | };
9 |
10 | exports.testStringIODelimiterForEach = function () {
11 | var stringio = new io.StringIO("a\0b\0", "\0");
12 | var acc = [];
13 | stringio.forEach(function (line) {
14 | acc.push(line);
15 | });
16 | assert.eq(["a", "b"], acc);
17 | };
18 |
19 |
20 | if (require.main == module.id)
21 | require("os").exit(require("test/runner").run(exports));
22 |
--------------------------------------------------------------------------------
/tests/io/textinputstream.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 |
3 | exports.testTextInputStreamReadUnicodeOnBoundary = function() {
4 | var str = Array(1024).join(" ") + "ü";
5 | try {
6 | system.fs.write("testTextInputStreamReadUnicodeOnBoundary", str, { charset : "UTF-8" });
7 | var b = system.fs.read("testTextInputStreamReadUnicodeOnBoundary", "b");
8 | var strA = b.decodeToString("UTF-8");
9 | assert.eq(str, strA);
10 | } finally {
11 | system.fs.remove("testTextInputStreamReadUnicodeOnBoundary");
12 | }
13 | }
14 |
15 | if (require.main === module.id)
16 | require("os").exit(require("test/runner").run(exports));
17 |
--------------------------------------------------------------------------------
/tests/os/all-tests.js:
--------------------------------------------------------------------------------
1 | exports.testPopen = require("./popen");
2 | exports.testSystem = require("./system");
3 | exports.testParse = require("./parse")
4 | if (require.main == module.id)
5 | require("os").exit(require("test/runner").run(exports));
6 |
--------------------------------------------------------------------------------
/tests/os/parse-fuzzer.js:
--------------------------------------------------------------------------------
1 | var OS = require("os");
2 | var ASSERT = require("assert");
3 | var UTIL = require("UTIL");
4 | var stream = require("term").stream;
5 |
6 | // config
7 | var random = false;
8 | var maxLength = 10;
9 | var tokens = ["x", "'", '"', " ", "\\"];
10 |
11 | function shellParse(argString) {
12 | // print(argString)
13 | var p = OS.popen(["sh", "-c", 'for i in "$@"; do echo "$i"; done', "--"].map(OS.enquote).join(" ") + " " + argString);
14 | var x = p.stdout.read();
15 | // print("["+x+"]")
16 | var result = x.split("\n").slice(0,-1);
17 | if (p.wait())
18 | throw result;
19 | return result;
20 | }
21 |
22 | var testIndex = -1;
23 | function buildTestString() {
24 |
25 | if (random) {
26 | var components = [];
27 | var n = Math.round(Math.random()*maxLength);
28 | while (components.length < n)
29 | components.push(tokens[Math.floor(Math.random()*tokens.length)]);
30 | return components.join("");
31 | }
32 | else {
33 | var index = testIndex++;
34 | if (index < 0)
35 | return "";
36 | // convert to a base tokens.length number and replace each digit with corresponding token
37 | return index.toString(tokens.length).replace(/./g, function(x) {
38 | return tokens[parseInt(x, tokens.length)];
39 | });
40 | }
41 | }
42 |
43 | while (true) {
44 | var argString = buildTestString();
45 |
46 | try {
47 | var expectedArgs = shellParse(argString);
48 | } catch (e) {
49 | // TODO: test invalid behavior matches?
50 | continue;
51 | }
52 |
53 | var actualArgs = OS.parse(argString);
54 |
55 | var pass = UTIL.eq(expectedArgs, actualArgs);
56 |
57 | stream.print("[" + testIndex + "] " + (pass ? "\0green(PASS\0)" : "\0red(FAIL\0)") +
58 | ": string=["+argString+"] expected=["+expectedArgs+"]("+expectedArgs.length+") actual=["+actualArgs+"]("+actualArgs.length+")");
59 | }
60 |
--------------------------------------------------------------------------------
/tests/os/popen.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var os = require("os");
3 | var io = require("io");
4 |
5 | exports.testArrayCommunicateStdout = function () {
6 | var list = io.StringIO();
7 | list.print("30");
8 | list.print("4");
9 | list.print("1000");
10 | list.print("200");
11 |
12 | var process = os.popen(["sort", "-n", "-"]);
13 | var lines = [];
14 | process.communicate(list).stdout.forEach(function (line) {
15 | lines.push(line);
16 | });
17 |
18 | assert.eq(["4", "30", "200", "1000"], lines);
19 | };
20 |
21 | exports.testCommunicateStatus = function () {
22 | assert.eq(255, os.popen("exit -1").communicate().status);
23 | assert.eq(255, os.popen("exit -1").wait());
24 | };
25 |
26 | exports.testCommunicateStdout = function () {
27 | assert.eq("hi\n", os.popen("echo hi").communicate().stdout.read());
28 | assert.eq("hi\n", os.popen("cat").communicate("hi").stdout.read());
29 | };
30 |
31 | exports.testCommunicateStderr = function () {
32 | assert.eq("hi\n", os.popen("echo hi >&2").communicate().stderr.read());
33 | };
34 |
35 | exports.testCommunicateStdin = function () {
36 | assert.eq("", os.popen("exit 0").communicate("hi").stdin.read());
37 | };
38 |
39 | var charsets = ["UTF-8", "UTF-16"];
40 | var testString = "I ♥ JS";
41 |
42 | exports.testRawStreams = function() {
43 | charsets.forEach(function(charset) {
44 | var p = os.popen(["cat"]);
45 | p.stdin.raw.write(testString.toByteString(charset)).flush().close();
46 | var result = p.stdout.raw.read().decodeToString(charset);
47 | assert.eq(testString, result);
48 | });
49 | };
50 |
51 | exports.testCharsetInputStream = function() {
52 | charsets.forEach(function(charset) {
53 | var p = os.popen(["cat"], { charset : charset });
54 | p.stdin.write(testString).flush().close();
55 | var result = p.stdout.raw.read().decodeToString(charset);
56 | assert.eq(testString, result);
57 | p.stdout.close();
58 | p.stderr.close();
59 | });
60 | };
61 |
62 | exports.testCharsetOutputStream = function() {
63 | charsets.forEach(function(charset) {
64 | var p = os.popen(["cat"], { charset : charset });
65 | p.stdin.raw.write(testString.toByteString(charset)).flush().close();
66 | var result = p.stdout.read();
67 | assert.eq(testString, result);
68 | p.stdout.close();
69 | p.stderr.close();
70 | });
71 | };
72 |
73 |
74 | if (require.main == module.id)
75 | os.exit(require("test/runner").run(exports));
76 |
77 |
--------------------------------------------------------------------------------
/tests/os/system.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var os = require("os");
3 |
4 | // FIXME: these will probably fail on Windows
5 | var systemTests = [
6 | ["true", 0],
7 | ["false", 1],
8 | ["exit 2", 2],
9 | ["exit 255", 255],
10 | ["exit 256", 0],
11 | ["exit 257", 1]
12 | ]
13 |
14 | systemTests.forEach(function(test) {
15 | exports["test system('"+test[0]+"') == " + test[1]] = function() {
16 | assert.eq(test[1], os.system(test[0]))
17 | }
18 | });
19 |
20 | if (require.main === module.id)
21 | os.exit(require("test/runner").run(exports));
22 |
23 |
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/lib/main.js:
--------------------------------------------------------------------------------
1 |
2 | var UTIL = require("util");
3 | var FILE = require("file");
4 | var ASSERT = require("assert");
5 |
6 | exports.getInfo = function(visited) {
7 |
8 | visited = visited || [];
9 |
10 | var basePath = FILE.Path(module.path);
11 | while(basePath.basename()!="_files") {
12 | basePath = basePath.dirname();
13 | }
14 |
15 | var info = {
16 | "id": basePath.relative(module.id).valueOf(),
17 | "path": basePath.relative(module.path).valueOf(),
18 | "package": module["package"],
19 | "using": module.using
20 | }
21 |
22 | if(UTIL.has(visited, info.id)) {
23 | return "RECURSION";
24 | }
25 | visited.push(info.id);
26 |
27 | if(UTIL.len(module.using)>0) {
28 | info.subInfo = {};
29 | UTIL.every(module.using, function(item) {
30 | var preVisited = UTIL.copy(visited);
31 | var subInfo = require("main", item[0]).getInfo(visited);
32 | ASSERT.deepEqual(
33 | subInfo,
34 | require("main", item[1]).getInfo(preVisited)
35 | );
36 | info.subInfo[item[0]] = subInfo;
37 |
38 | });
39 | } else {
40 | if(info.id=="_files/test-sea/lib/main") {
41 | info.subInfo = require("main", "test-package-1").getInfo(visited);
42 | }
43 | }
44 |
45 | return info;
46 | }
47 |
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "test-sea",
3 | "dependencies": [
4 | "test-package-1"
5 | ]
6 | }
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/packages/test-package-1/lib:
--------------------------------------------------------------------------------
1 | ../../lib
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/packages/test-package-1/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "test-package-1",
3 | "dependencies": [
4 | "domain.com/path/to/package1",
5 | "test-package-2"
6 | ],
7 | "using": {
8 | "my-package-a": {
9 | "location": "http://domain.com/path/to/package1/"
10 | },
11 | "my-package-b": {
12 | "catalog": "http://domain.com/path/to/catalog/catalog.json",
13 | "name": "package2"
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/packages/test-package-2/lib:
--------------------------------------------------------------------------------
1 | ../../lib
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/packages/test-package-2/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "test-package-2",
3 | "using": {
4 | "my-package-a": {
5 | "catalog": "http://domain.com/path/to/catalog/catalog.json",
6 | "name": "package2"
7 | },
8 | "my-package-b": {
9 | "location": "http://domain.com/path/to/package1/"
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/using/domain.com/path/to/catalog/package2/lib:
--------------------------------------------------------------------------------
1 | ../../../../../../lib
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/using/domain.com/path/to/catalog/package2/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "package2",
3 | "using": {
4 | "my-package-1": {
5 | "location": "http://domain.com/path/to/package1/"
6 | }
7 | }
8 | }
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/using/domain.com/path/to/package1/lib:
--------------------------------------------------------------------------------
1 | ../../../../../lib
--------------------------------------------------------------------------------
/tests/package/_files/test-sea/using/domain.com/path/to/package1/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "package1",
3 | "using": {
4 | "my-package-a": {
5 | "catalog": "http://domain.com/path/to/catalog/catalog.json",
6 | "name": "package2"
7 | }
8 | }
9 | }
--------------------------------------------------------------------------------
/tests/sandbox/byte-io.js:
--------------------------------------------------------------------------------
1 |
2 | var fs = require('file');
3 | var file = fs.open(fs.resolve(module.path, 'utf-8.js'), 'rb');
4 | var content = file.read();
5 | print(typeof content);
6 | print(content.length);
7 | print('');
8 |
9 | var file = fs.open(fs.resolve(module.path, 'utf-8.js'), 'rt', {'charset': 'utf-8'});
10 | var content = file.read();
11 | print(typeof content);
12 | print(content.length);
13 | print('');
14 |
15 | var file = fs.open(fs.resolve(module.path, 'utf-8.js'), 'r');
16 | var content = file.read();
17 | print(typeof content);
18 | print(content.length);
19 | print('');
20 |
21 |
--------------------------------------------------------------------------------
/tests/sandbox/fileName.js:
--------------------------------------------------------------------------------
1 |
2 | print(module.path);
3 |
4 |
--------------------------------------------------------------------------------
/tests/sandbox/foo.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlrobinson/narwhal/048adb303e193f9730a40fa6e458ae652cbc4786/tests/sandbox/foo.js
--------------------------------------------------------------------------------
/tests/sandbox/reload.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require("util");
3 | var assert = require("test/assert");
4 | var args = require("args");
5 | var sandboxing = require("sandbox");
6 | var loader = require("loader");
7 | var os = require("os");
8 |
9 | exports.test = function () {
10 |
11 | var accumulator = [];
12 | var subprint = function (text) {
13 | accumulator.push(text);
14 | };
15 |
16 | var supersandbox = sandboxing.Sandbox({
17 | 'loader': require.loader,
18 | 'print': subprint
19 | });
20 |
21 | var path = system.fs.path(module.path).resolve('./foo.js');
22 | var id = path.toString();
23 | var subsandboxing = supersandbox('sandbox');
24 |
25 | var subloader = loader.Loader({
26 | 'paths': require.loader.paths,
27 | 'debug': true
28 | });
29 |
30 | var sandbox1 = subsandboxing.Sandbox({
31 | 'loader': subloader,
32 | 'print': subprint
33 | });
34 |
35 | path.touch();
36 | os.sleep(1);
37 | assert.eq(0, accumulator.length);
38 |
39 | sandbox1(id);
40 | // must be loaded
41 | assert.eq(1, accumulator.length, '1.1');
42 |
43 | sandbox1(id);
44 | // must be cached
45 | assert.eq(1, accumulator.length, '1.2');
46 |
47 | var sandbox2 = subsandboxing.Sandbox({
48 | 'loader': subloader,
49 | 'print': subprint
50 | });
51 |
52 | sandbox2(id);
53 | // must still be cached in the loader
54 | assert.eq(1, accumulator.length, '2.1');
55 | path.touch();
56 | os.sleep(1);
57 | // still cached, although it has changed
58 | assert.eq(1, accumulator.length, '2.2');
59 | sandbox2(id);
60 | // still cached, although it has changed
61 | assert.eq(1, accumulator.length, '2.3');
62 |
63 | var sandbox3 = subsandboxing.Sandbox({
64 | 'loader': subloader,
65 | 'print': subprint
66 | });
67 |
68 | assert.eq(1, accumulator.length, '3.1');
69 | // cached, but changed
70 | sandbox3(id);
71 | // reloaded
72 | assert.eq(2, accumulator.length, '3.2');
73 | sandbox3(id);
74 | assert.eq(2, accumulator.length, '3.3');
75 |
76 | }
77 |
78 | if (require.main == module.id)
79 | require("os").exit(require("test/runner").run(exports));
80 |
81 |
--------------------------------------------------------------------------------
/tests/uri.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var util = require("util");
3 |
4 | var uri = require("uri");
5 | var URI = uri.URI;
6 |
7 | exports.testConstructor = function() {
8 | var uri = new URI("http://www.narwhaljs.org/blog/categories?id=news");
9 |
10 | assert.isEqual("http", uri.scheme);
11 | assert.isEqual("www.narwhaljs.org", uri.authority);
12 | assert.isEqual("/blog/categories", uri.path);
13 | assert.isEqual("id=news", uri.query);
14 | assert.isNull(uri.fragment);
15 | }
16 |
17 | exports.testToString = function() {
18 | var uri = new URI("http://www.narwhaljs.org/blog/categories?id=news");
19 | assert.isEqual("http://www.narwhaljs.org/blog/categories?id=news", uri.toString());
20 | }
21 |
22 | util.forEachApply([
23 | ["/foo/bar/baz", "/foo/bar/quux", "quux"],
24 | ["/foo/bar/baz", "/foo/bar/quux/asdf", "quux/asdf"],
25 | ["/foo/bar/baz", "/foo/bar/quux/baz", "quux/baz"],
26 | ["/foo/bar/baz", "/foo/quux/baz", "../quux/baz"]
27 | ], function (from, to, expected) {
28 | exports[
29 | 'testRelative ' +
30 | 'from: ' + util.repr(from) + ' ' +
31 | 'to: ' + util.repr(to) + ' ' +
32 | 'is: ' + util.repr(expected)
33 | ] = function () {
34 | var actual = uri.relative(from, to);
35 | assert.eq(expected, actual);
36 | };
37 | });
38 |
39 | if (require.main == module.id)
40 | require("os").exit(require("test/runner").run(exports));
41 |
42 |
--------------------------------------------------------------------------------
/tests/util/all-tests.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testOperator = require("./operator");
6 | exports.testObject = require("./object");
7 | exports.testArray = require("./array");
8 | exports.testCollection = require("./collection");
9 | exports.testString = require("./string");
10 | exports.testRange = require("./range");
11 | exports.testCase = require("./case");
12 | exports.testUnique = require("./unique");
13 |
14 | exports.testNo = function () {
15 | assert.isTrue(util.no(undefined));
16 | assert.isTrue(util.no(null));
17 | assert.isFalse(util.no(0));
18 | assert.isFalse(util.no(false));
19 | };
20 |
21 | exports.testApply = function () {
22 | // XXX
23 | };
24 |
25 | exports.testCopyUndefined = function () {
26 | assert.eq(undefined, util.copy(undefined));
27 | };
28 |
29 | exports.testCopyNull = function () {
30 | assert.eq(null, util.copy(null));
31 | };
32 |
33 | exports.testCopyNumber = function () {
34 | assert.eq(1, util.copy(1));
35 | };
36 |
37 | exports.testCopyDate = function () {
38 | var date = new Date();
39 | assert.eq(date, util.copy(date));
40 | };
41 |
42 | /*
43 | exports.testDeepCopy = function () {
44 | };
45 | */
46 |
47 | exports.testRepr = require("./repr");
48 |
49 | /*
50 | exports.testIs = function () {
51 | };
52 |
53 | */
54 |
55 | exports.testEq = require("./eq");
56 |
57 | /*
58 | exports.testNe = function () {
59 | };
60 |
61 | exports.testLt = function () {
62 | };
63 |
64 | exports.testGt = function () {
65 | };
66 |
67 | exports.testLe = function () {
68 | };
69 |
70 | exports.testGe = function () {
71 | };
72 |
73 | exports.testCompare = function () {
74 | };
75 | */
76 |
77 | if (require.main == module.id)
78 | require("os").exit(require("test/runner").run(exports));
79 |
80 |
--------------------------------------------------------------------------------
/tests/util/array/is-arguments.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testArray = function () {
6 | assert.isFalse(util.isArguments([]));
7 | assert.isFalse(util.isArguments([1, 2, 3]));
8 | };
9 |
10 | exports.testArguments = function () {
11 | assert.isTrue(util.isArguments(arguments));
12 | };
13 |
14 | exports.testArgumentsReturned = function () {
15 | assert.isTrue(util.isArguments((function () {
16 | return arguments;
17 | })()));
18 | };
19 |
20 | exports.testNegativeDuckType = function () {
21 | assert.isFalse(util.isArguments({
22 | "length": 1,
23 | "0": 1
24 | }));
25 | };
26 |
27 | if (require.main == module.id)
28 | require("os").exit(require("test/runner").run(exports));
29 |
30 |
--------------------------------------------------------------------------------
/tests/util/array/is-array-like.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testArray = function () {
6 | assert.isTrue(util.isArrayLike([]));
7 | assert.isTrue(util.isArrayLike([1, 2, 3]));
8 | };
9 |
10 | exports.testArguments = function () {
11 | assert.isTrue(util.isArrayLike(arguments));
12 | };
13 |
14 | exports.testArgumentsReturned = function () {
15 | assert.isTrue(util.isArrayLike((function () {
16 | return arguments;
17 | })()));
18 | };
19 |
20 | exports.testNegativeDuckType = function () {
21 | assert.isFalse(util.isArrayLike({
22 | "length": 1,
23 | "0": 1
24 | }));
25 | };
26 |
27 | if (require.main == module.id)
28 | require("os").exit(require("test/runner").run(exports));
29 |
30 |
--------------------------------------------------------------------------------
/tests/util/case.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | /* upper, lower, camel, title, splitName, joinName */
6 |
7 | if (require.main == module.id)
8 | require("os").exit(require("test/runner").run(exports));
9 |
10 |
--------------------------------------------------------------------------------
/tests/util/collection.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | /*
6 | exports.testKeys = function () {
7 | };
8 |
9 | exports.testValues = function () {
10 | };
11 |
12 | exports.testItems = function () {
13 | };
14 |
15 | exports.testLen = function () {
16 | };
17 |
18 | exports.testHas = function () {
19 | };
20 |
21 | */
22 |
23 | exports.testGetObject = function () {
24 | assert.eq(10, util.get({'a': 10}, 'a'));
25 | };
26 |
27 | exports.testGetObjectKeyError = function () {
28 | assert.throwsError(function () {
29 | util.get({'a': 10}, 'b');
30 | });
31 | };
32 |
33 | exports.testGetObjectDefault = function () {
34 | assert.eq(20, util.get({'a': 10}, 'b', 20));
35 | };
36 |
37 | exports.testGetNonPolymorphic = function () {
38 | var foo = {"get": 10};
39 | assert.eq(10, util.get(foo, "get"));
40 | };
41 |
42 | exports.testGetPolymorphic = function () {
43 | var foo = Object.create({"get": function () {
44 | return 10;
45 | }});
46 | assert.eq(10, util.get(foo, "get"));
47 | };
48 |
49 | exports.testGetArray = function () {
50 | assert.eq(1, util.get([1,2,3], 0));
51 | };
52 |
53 | exports.testGetArrayKeyError = function () {
54 | assert.throwsError(function () {
55 | util.get([1,2,3], 4);
56 | });
57 | };
58 |
59 | exports.testGetArrayDefault = function () {
60 | assert.eq(3, util.get([1,2,3], 4, 3));
61 | };
62 |
63 | /*
64 | exports.testGetArrayNeg = function () {
65 | assert.eq(3, util.get([1,2,3], -1));
66 | };
67 | */
68 |
69 | exports.testGetString = function () {
70 | assert.eq('a', util.get('abc', 0));
71 | assert.eq('b', util.get('abc', 1));
72 | };
73 |
74 | /*
75 |
76 | exports.testGetStringNeg = function () {
77 | assert.eq('c', util.get('abc', -1));
78 | };
79 |
80 | exports.testSet = function () {
81 | };
82 |
83 | exports.testGetset = function () {
84 | };
85 |
86 | exports.testDel = function () {
87 | };
88 |
89 | exports.testCut = function () {
90 | };
91 |
92 | exports.testPut = function () {
93 | };
94 |
95 | exports.testUpdate = function () {
96 | };
97 |
98 | exports.testComplete = function () {
99 | };
100 | */
101 |
102 | if (require.main == module.id)
103 | require("os").exit(require("test/runner").run(exports));
104 |
105 |
--------------------------------------------------------------------------------
/tests/util/complete.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var util = require("util");
3 |
4 | exports["test completes key"] = function() {
5 | assert.eq("world", util.complete({}, { hello: "world" }).hello);
6 | };
7 |
8 | exports["test does not complete key"] = function() {
9 | assert.eq("usa", util.complete({
10 | hello: "usa"
11 | }, {
12 | hello: "world"
13 | }).hello);
14 | };
15 |
16 | if (require.main == module.id)
17 | require("test/runner").run(exports);
18 |
--------------------------------------------------------------------------------
/tests/util/eq.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testUndefined = function () {
6 | assert.isTrue(util.eq(undefined, undefined));
7 | };
8 |
9 | exports.testNull = function () {
10 | assert.isTrue(util.eq(null, null));
11 | };
12 |
13 | exports.testNumber = function () {
14 | assert.isTrue(util.eq(1, 1));
15 | };
16 |
17 | exports.testNaN = function () {
18 | assert.isFalse(util.eq(NaN, NaN));
19 | };
20 |
21 | exports.testObject = function () {
22 | assert.isTrue(util.eq({"a": 10}, {"a": 10}));
23 | };
24 |
25 | exports.testObjectNegativePrototype = function () {
26 | function Type() {};
27 | Type.prototype.a = 10;
28 | var object = new Type();
29 | assert.isFalse(util.eq({"a": 10}, object));
30 | };
31 |
32 | exports.testArray = function () {
33 | assert.isTrue(util.eq([1,2,3], [1,2,3]));
34 | };
35 |
36 | exports.testArguments = function () {
37 | var args = (function () {return arguments})(1, 2, 3);
38 | assert.isTrue(util.eq([1, 2, 3], args));
39 | };
40 |
41 | exports.testPolymorphic = function () {
42 | function Type() {};
43 | Type.prototype.eq = function () {
44 | return true;
45 | };
46 | assert.isTrue(util.eq(new Type(), [1,2,3]));
47 | };
48 |
49 | exports.testCurry = function () {
50 | assert.isTrue(util.eq()());
51 | assert.isTrue(util.eq(10)(10));
52 | assert.isFalse(util.eq(10)(20));
53 | };
54 |
55 | if (require.main == module.id)
56 | require("os").exit(require("test/runner").run(exports));
57 |
58 |
--------------------------------------------------------------------------------
/tests/util/expand.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | var expandOracle = function (line, tabLength, initial) {
6 | if (!tabLength) tabLength = 4;
7 | if (initial === undefined) initial = 0;
8 | var at = initial;
9 | var result = '';
10 | for (var i = 0; i < line.length; i++) {
11 | var c = line.charAt(i);
12 | if (c == "\n") {
13 | at = initial;
14 | result += c;
15 | } else if (c == "\r") {
16 | result += c;
17 | } else if (c == "\t") {
18 | var next = (at & ~(tabLength - 1)) + tabLength;
19 | result += util.mul(' ', next - at);
20 | at = next;
21 | } else {
22 | at++;
23 | result += c;
24 | }
25 | }
26 | return result;
27 | };
28 |
29 | var inputs = [
30 | "\t",
31 | " \t",
32 | " \t",
33 | " \t",
34 | "\t\t"
35 | ];
36 |
37 | util.forEach(inputs, function (input) {
38 | exports['test ' + util.repr(input)] = function () {
39 | assert.eq(expandOracle(input), util.expand(input));
40 | };
41 | });
42 |
43 | if (require.main == module.id)
44 | require("os").exit(require("test/runner").run(exports));
45 |
46 |
--------------------------------------------------------------------------------
/tests/util/operator.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require('test/assert');
3 | var util = require("util");
4 |
5 | exports.testNegative = function () {
6 | var foo = {"repr": 10};
7 | assert.eq('{"repr": 10}', util.repr(foo));
8 | };
9 |
10 | exports.testPositive = function () {
11 | var Foo = function () {
12 | };
13 | Foo.prototype.repr = function () {
14 | return "Foo()";
15 | };
16 | assert.eq("Foo()", util.repr(new Foo()));
17 | };
18 |
19 | exports.testCurry = function () {
20 | var lt10 = util.lt(10);
21 | assert.isTrue(lt10(5));
22 | };
23 |
24 | if (module.id == require.main)
25 | require("os").exit(require("test/runner").run(exports));
26 |
--------------------------------------------------------------------------------
/tests/util/range.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testRange1 = function () {
6 | assert.eq([0, 1, 2], util.range(3));
7 | };
8 |
9 | exports.testRange2 = function () {
10 | assert.eq([1, 2, 3], util.range(1, 4));
11 | };
12 |
13 | exports.testRange3 = function () {
14 | assert.eq([2, 4, 6], util.range(2, 8, 2));
15 | };
16 |
17 | if (require.main === module.id)
18 | require("os").exit(require("test/runner").run(exports));
19 |
20 |
--------------------------------------------------------------------------------
/tests/util/repr.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.testObject = function () {
6 | assert.eq('{"a": 10}', util.repr({"a": 10}));
7 | };
8 |
9 | exports.testArray = function () {
10 | assert.eq('[1, 2, 3]', util.repr([1, 2, 3]));
11 | };
12 |
13 | exports.testArguments = function () {
14 | var args = (function () {return arguments})(1, 2, 3);
15 | assert.eq('[1, 2, 3]', util.repr(args));
16 | };
17 |
18 | /*
19 | exports.testType = function () {
20 | assert.eq('', util.repr());
21 | };
22 | */
23 |
24 | if (require.main == module.id)
25 | require("os").exit(require("test/runner").run(exports));
26 |
27 |
--------------------------------------------------------------------------------
/tests/util/string.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | /*
6 | exports.testEscape = function () {
7 | };
8 |
9 | exports.testEnquote = function () {
10 | };
11 | */
12 |
13 | exports.testExpand = require("./expand");
14 |
15 | /*
16 | exports.testTrim = function () {
17 | };
18 |
19 | exports.testTrimBegin = function () {
20 | };
21 |
22 | exports.testTrimEnd = function () {
23 | };
24 |
25 | exports.testPadBegin = function () {
26 | };
27 |
28 | exports.testPadEnd = function () {
29 | };
30 | */
31 |
32 | if (require.main == module.id)
33 | require("os").exit(require("test/runner").run(exports));
34 |
35 |
--------------------------------------------------------------------------------
/tests/util/unique.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("util");
4 |
5 | exports.test = function () {
6 | assert.eq([3, 2, 1], util.unique([3, 2, 3, 1, 2, 3]));
7 | assert.eq(['toString', 'hasOwnProperty'], util.unique(['toString', 'hasOwnProperty']));
8 | };
9 |
10 | if (require.main == module.id)
11 | require("os").exit(require("test/runner").run(exports));
12 |
13 |
--------------------------------------------------------------------------------
/tests/util/update.js:
--------------------------------------------------------------------------------
1 | var assert = require("test/assert");
2 | var util = require("util");
3 |
4 | exports["test returns updated object"] = function() {
5 | var obj = {};
6 | var obj2 = { hello: "world" };
7 |
8 | var result = util.update(obj, obj2);
9 |
10 | assert.eq(result, obj);
11 | };
12 |
13 | exports["test is variadic"] = function() {
14 | var obj = util.update({}, { a: 1 }, { b: 2});
15 |
16 | assert.eq(1, obj.a);
17 | assert.eq(2, obj.b);
18 | };
19 |
20 | exports["test last in wins for multiple sources"] = function() {
21 | var obj = util.update({}, { a: 1 }, { a: 2});
22 |
23 | assert.eq(2, obj.a);
24 | };
25 |
26 | if (module.id == require.main)
27 | require("test/runner").run(exports);
28 |
--------------------------------------------------------------------------------