├── .gitignore
├── README.md
├── bin
├── .gitignore
├── activate
├── activate.bash
├── activate.cmd
├── 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
├── 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-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
│ │ └── xhr.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
│ │ ├── 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-loop-engine.js
│ │ ├── event-queue.js
│ │ ├── events-engine.js
│ │ ├── file-engine.js
│ │ ├── fs-base.js
│ │ ├── http-client-engine.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
├── event-loop-hook.js
├── event-loop-setup.js
├── event-loop.js
├── events.js
├── file-bootstrap.js
├── file.js
├── fs-bootstrap.js
├── hash.js
├── hashp.js
├── http-client.js
├── http.js
├── http
│ └── fs-store.js
├── io.js
├── jsmin.js
├── jsonpath.js
├── narwhal.js
├── narwhal
│ ├── client.js
│ ├── compile.js
│ ├── console.js
│ ├── env.js
│ ├── inline.js
│ ├── json.js
│ ├── json.md
│ ├── repl-worker.js
│ ├── repl.js
│ ├── server-test.js
│ ├── server.js
│ └── tusk
│ │ └── support.js
├── os.js
├── ref-send.html
├── test
│ ├── assert.js
│ ├── equiv.js
│ ├── jsdump.js
│ └── runner.js
└── unload.js
├── local.json.template
├── narwhal.conf.template
├── narwhal.gemspec
├── narwhal.js
├── package.json
├── packages
├── .gitignore
├── narwhal-lib
│ ├── lib
│ │ ├── args.js
│ │ ├── assert.js
│ │ ├── base16.js
│ │ ├── base64.js
│ │ ├── crc32.js
│ │ ├── html.js
│ │ ├── ini.js
│ │ ├── loader.js
│ │ ├── loader
│ │ │ └── multi.js
│ │ ├── logger.js
│ │ ├── md4.js
│ │ ├── md5.js
│ │ ├── mime.js
│ │ ├── narwhal
│ │ │ ├── args.js
│ │ │ ├── deprecated.js
│ │ │ ├── loader.js
│ │ │ ├── loader
│ │ │ │ ├── attenuated.js
│ │ │ │ ├── multi.js
│ │ │ │ └── prefix.js
│ │ │ ├── packages.js
│ │ │ ├── promise.js
│ │ │ ├── sandbox.js
│ │ │ ├── term.js
│ │ │ └── util.js
│ │ ├── packages.js
│ │ ├── printf.js
│ │ ├── promise.js
│ │ ├── querystring.js
│ │ ├── sandbox.js
│ │ ├── sha.js
│ │ ├── sha256.js
│ │ ├── struct.js
│ │ ├── term.js
│ │ ├── test.js
│ │ ├── uri.js
│ │ ├── utf8.js
│ │ ├── util.js
│ │ ├── uuid.js
│ │ └── xregexp.js
│ └── package.json
├── readline
│ ├── engines
│ │ ├── default
│ │ │ └── lib
│ │ │ │ ├── readline.js
│ │ │ │ └── readlineJS.js
│ │ └── rhino
│ │ │ └── lib
│ │ │ ├── readline.js
│ │ │ └── readlineJS.js
│ └── package.json
├── tusk
│ ├── README.md
│ ├── bin
│ │ ├── tusk
│ │ └── tusk.cmd
│ ├── docs
│ │ ├── catalog.md
│ │ ├── package.md
│ │ └── sea.md
│ ├── lib
│ │ ├── 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
│ │ │ └── update.js
│ └── package.json
└── zip
│ ├── README
│ ├── lib
│ ├── inflate.js
│ ├── unzip.js
│ └── zip.js
│ ├── package.json
│ └── tests
│ ├── all-tests.js
│ ├── inflate-tests.js
│ └── zip-tests.js
├── sources.json
└── tests
├── all-tests.js
├── args.js
├── args
├── actions.js
├── choices.js
├── commands.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
├── promise.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/js:
--------------------------------------------------------------------------------
1 | narwhal
--------------------------------------------------------------------------------
/bin/json:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 | require("narwhal/json").main(system);
3 |
--------------------------------------------------------------------------------
/bin/narwhal:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env 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 JAVA_HOME is set, prepend JAVA_HOME/bin to PATH so correct JVM is used
30 | if [ -d "$JAVA_HOME" ]; then
31 | export PATH=$JAVA_HOME/bin:$PATH
32 | fi
33 |
34 | if [ -n "$NARWHAL_DEBUG" ]; then
35 | export NARWHAL_DEBUG
36 | fi
37 |
38 | # if NARWHAL_ENGINE isn't yet set, set it to the default engine, and export it
39 | if [ -z "$NARWHAL_ENGINE" ]; then
40 | NARWHAL_ENGINE=$NARWHAL_DEFAULT_ENGINE
41 | fi
42 | export NARWHAL_HOME
43 |
44 | # build the executable name for the engine
45 | EXECUTABLE_NAME="narwhal-$NARWHAL_ENGINE"
46 |
47 | # search for the engine home directory
48 | # try narwhal.conf setting
49 | if [ "$NARWHAL_ENGINE_HOME" ]; then
50 | export NARWHAL_ENGINE_HOME=$(cd -P -- "$NARWHAL_HOME" && cd -P -- "$NARWHAL_ENGINE_HOME" && pwd -P)
51 | # try relative, engines
52 | elif [ -f "$NARWHAL_HOME/engines/$NARWHAL_ENGINE/bin/$EXECUTABLE_NAME" ]; then
53 | export NARWHAL_ENGINE_HOME="$NARWHAL_HOME/engines/$NARWHAL_ENGINE"
54 | # try relative, packages
55 | elif [ -f "$NARWHAL_HOME/packages/narwhal-$NARWHAL_ENGINE/bin/$EXECUTABLE_NAME" ]; then
56 | export NARWHAL_ENGINE_HOME="$NARWHAL_HOME/packages/narwhal-$NARWHAL_ENGINE"
57 | # try $PATH
58 | elif which -s "$EXECUTABLE_NAME"; then
59 | EXECUTABLE_PATH=$(which "$EXECUTABLE_NAME")
60 | # resolve symlinks
61 | while [ -h "$EXECUTABLE_PATH" ]; do
62 | DIR=$(dirname -- "$EXECUTABLE_PATH")
63 | SYM=$(readlink -- "$EXECUTABLE_PATH")
64 | EXECUTABLE_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
65 | done
66 | export NARWHAL_ENGINE_HOME=$(dirname -- "$(dirname -- "$EXECUTABLE_PATH")")
67 | else
68 | echo "Can't find executable for $NARWHAL_ENGINE"
69 | exit 1
70 | fi
71 |
72 | exec "$NARWHAL_ENGINE_HOME"/bin/"$EXECUTABLE_NAME" "$@"
73 |
--------------------------------------------------------------------------------
/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 | #!/usr/bin/env 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('tusk').main(system.args);
7 |
8 |
--------------------------------------------------------------------------------
/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/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/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 |
--------------------------------------------------------------------------------
/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/browser/lib/xhr.js:
--------------------------------------------------------------------------------
1 |
2 | exports.XmlHttpRequest = function () {
3 | /*
4 |
5 | subscribes to the lazy function definition pattern, since it
6 | redefines itself as the first method that works on the first
7 | call.
8 |
9 | Some other AJAX implementations check
10 | - Msxml2.XMLHTTP.6.0
11 | - Msxml2.XMLHTTP.5.0
12 | - Msxml2.XMLHTTP.4.0
13 | - Msxml2.XMLHTTP.3.0
14 | - Microsoft.XMLHTTP
15 |
16 | Microsoft.XMLHTTP is an older name-space, but is equivalent to
17 | the more lucid Msxml2.XMLHTTP.3.0 and only available when the
18 | latter is available too.
19 |
20 | Msxml2.XMLHTTP.4.0 has been superseded and is currently only
21 | intended to support legacy applications.
22 |
23 | Msxml2.XMLHTTP.5.0 was shipped with MS Office 2003 and was
24 | intended for Office applications. IE7 has this component off
25 | by default in the Internet zone, leading to canary-yellow
26 | verification dialogs.
27 |
28 | Msxml2.XMLHTTP.6.0 is currently the standard MS is pushing.
29 | I originally left out 6.0 since it would increase the burden
30 | of testing for functionality that cannot be trusted to work
31 | in all browsers.
32 | However, I've taken Jonathan Snook's advice to check for
33 | Microsoft's latest and greatest.
34 |
35 | see: http://snook.ca/archives/javascript/xmlhttprequest_activex_ie/
36 |
37 | Msxml2.XMLHTTP.3.0 is the most widely deployed version and is
38 | serviced regularly with the OS for security and other reasons.
39 | It is MS's preferred alternative to MSXML6.
40 |
41 | see: http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
42 |
43 | see: http://www.telerik.com/documents/AJAX%20Page/Ajax-Part1.pdf page 3
44 |
45 | */
46 |
47 | var trials = [
48 | function () {return new XMLHttpRequest()},
49 | function () {return new ActiveXObject("Msxml2.XMLHTTP.6.0")},
50 | function () {return new ActiveXObject("Msxml2.XMLHTTP.3.0")},
51 | function () {throw new Error("No HTTP Request object available for your environment.")}
52 | ];
53 |
54 | var trial, result, exception;
55 | for (var i = 0; i < trials.length; i++) {
56 | exception = undefined;
57 | /* redeclare for posterity */
58 | exports.XmlHttpRequest = trial = trials[i];
59 | try {
60 | result = trial();
61 | } catch (trialException) {
62 | exception = trialException;
63 | continue;
64 | }
65 | break;
66 | }
67 |
68 | if (exception) throw exception;
69 | else return result;
70 | };
71 |
72 |
--------------------------------------------------------------------------------
/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/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 | #!/usr/bin/env 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 |
25 | JAVA_OPTS="-Dnarwhal.http_proxy=$http_proxy -Djava.awt.headless=true"
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 | exec $RLWRAP java $JAVA_OPTS $NARWHAL_JAVA_ARGUMENTS -cp "$BOOTCLASSPATH:$CLASSPATH" "$JAVA_MAIN" -f "$BOOTSTRAP" -f -
68 | else
69 | exec 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/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/engines/rhino/jars/jline.jar
--------------------------------------------------------------------------------
/engines/rhino/jars/jna.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/engines/rhino/jars/jna.jar
--------------------------------------------------------------------------------
/engines/rhino/jars/js.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/engines/rhino/jars/js.jar
--------------------------------------------------------------------------------
/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-loop-engine.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 | require("event-loop-hook").when(function () {
15 | if (exports.hasPendingEvents())
16 | exports.enterEventLoop(function () {
17 | exports.shutdown();
18 | });
19 | });
20 |
21 | exports.getNextEvent = function(){
22 | return queue.take();
23 | };
24 |
25 | exports.processNextEvent = function(mayWait){
26 | if(!mayWait && queue.isEmpty()){
27 | return false;
28 | }
29 | try{
30 | var next = queue.take();
31 | next();
32 | }catch(e){
33 | exports.enqueue(function(){
34 | if(typeof onerror === "function"){
35 | // trigger the onerror event in the worker if an error occurs
36 | try{
37 | onerror(e);
38 | }
39 | catch(e){
40 | // don't want an error here to go into an infinite loop!
41 | exports.defaultErrorReporter(e);
42 | }
43 | }
44 | else{
45 | exports.defaultErrorReporter(e);
46 | }
47 | });
48 |
49 |
50 | }
51 | return true;
52 | };
53 |
54 | exports.enterEventLoop = function(onidle){
55 | shuttingDown = false;
56 | loopLevel++;
57 | var currentLoopLevel = loopLevel;
58 | while(true){
59 |
60 | if (queue.isEmpty()) {
61 | // fire onidle events if a callback is provided
62 | if (onidle) {
63 | onidle();
64 | }
65 | if(shuttingDown){
66 | return;
67 | }
68 | }
69 | if (loopLevel < currentLoopLevel) {
70 | return;
71 | }
72 |
73 | exports.processNextEvent(true);
74 |
75 | }
76 |
77 | };
78 |
79 | exports.enqueue = function(task, priority){
80 | if(loopLevel > -1){
81 | queue.put(task); // priority is ignored for now until PriorityBlockingQueue is used
82 | }
83 | };
84 |
85 | exports.hasPendingEvents = function(){
86 | return !queue.isEmpty();
87 | }
88 |
89 | // based on Node's process.unloop();
90 | exports.unloop = function(){
91 | loopLevel--;
92 | };
93 |
94 | exports.shutdown = function(){
95 | shuttingDown = true;
96 | if(queue.isEmpty()){
97 | // if it is empty we need to kick start the event loop to make sure we get into the
98 | // the check for shuttingDown
99 | exports.enqueue(function(){});
100 | }
101 | };
102 |
103 | exports.defaultErrorReporter = function(e){
104 | print((e.rhinoException && e.rhinoException.printStackTrace()) || (e.name + ": " + e.message));
105 | };
106 |
107 |
--------------------------------------------------------------------------------
/engines/rhino/lib/event-queue.js:
--------------------------------------------------------------------------------
1 |
2 | require("narwhal").deprecated(
3 | "The event-queue module is deprecated in favor of event-loop-engine," +
4 | "which is the default engine implementation of the event loop system as" +
5 | "used by the event-loop and event-loop-setup modules.");
6 |
7 | var EXPORTS = require("event-loop");
8 | var UTIL = require("narwhal/util");
9 | UTIL.update(exports, EXPORTS);
10 |
11 |
--------------------------------------------------------------------------------
/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/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 | #!/usr/bin/env 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/event-loop-hook.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | /**
5 | * This module, likely to change, is exclusively for the
6 | * purpose of arranging for an "event-loop-engine" to begin
7 | * dispatching events when the initial thread of execution
8 | * runs to its completion.
9 | *
10 | * narwhal/narwhal.js checks whether this module has been
11 | * loaded after the main module returns and calls the
12 | * "emit" method. No module is intended to call "emit"
13 | * manually.
14 | */
15 |
16 | var observers = [];
17 |
18 | /**
19 | * Arrange for an observer function to be called after the
20 | * "main" module returns.
21 | *
22 | * @param observer {Function}
23 | * @returns undefined
24 | */
25 | exports.when = function (observer) {
26 | observers.unshift(observer);
27 | };
28 |
29 | /**
30 | * This method, called by the engine after the "main" module
31 | * returns, invokes all of the observers (intended to be a
32 | * single event loop runner registered by an
33 | * "event-loop-engine") in the order they were requested.
34 | */
35 | exports.emit = function () {
36 | observers.forEach(function (observer) {
37 | observer();
38 | });
39 | };
40 |
41 | exports.send = function () {
42 | require("narwhal/deprecated").deprecated("unload.send is deprecated; use " +
43 | "unload.emit or avoid calling this routine manually");
44 | exports.emit();
45 | };
46 |
47 |
--------------------------------------------------------------------------------
/lib/event-loop-setup.js:
--------------------------------------------------------------------------------
1 |
2 | var eventLoop;
3 |
4 | /**
5 | * Configures the system to use a particular event loop
6 | * implementation. The event loop must support the event
7 | * loop API:
8 | *
9 | * - setTimeout
10 | * - clearTimeout
11 | * - setInterval
12 | * - clearInterval
13 | * - enqueue is optional; if it is not provided, the
14 | * event-loop module will provide one in terms of
15 | * setTimeout(task, 0).
16 | *
17 | * @throws Error if an event loop has already been
18 | * configured.
19 | *
20 | */
21 | exports.setEventLoop = function (_eventLoop) {
22 | if (eventLoop)
23 | throw new Error("An event loop has already been loaded.");
24 | eventLoop = _eventLoop;
25 | };
26 |
27 | /**
28 | * Returns an event loop implementation. If no event loop
29 | * has been configured, configures the "event-loop-engine"
30 | * module as the default implementation. After this method
31 | * has been called, the event loop cannot be changed.
32 | * The "event-loop" module itself uses this method the first
33 | * time it is required.
34 | */
35 | exports.getEventLoop = function () {
36 | if (!eventLoop)
37 | eventLoop = require("event-loop-engine");
38 | return eventLoop;
39 | };
40 |
41 |
--------------------------------------------------------------------------------
/lib/event-loop.js:
--------------------------------------------------------------------------------
1 |
2 | var eventLoop = require("event-loop-setup").getEventLoop();
3 |
4 | exports.enqueue = eventLoop.enqueue || function (task) {
5 | setTimeout(function () {
6 | // uses a closure to ensure that any additional
7 | // parameters are laundered
8 | task();
9 | }, 0);
10 | };
11 |
12 | exports.setTimeout = eventLoop.setTimeout;
13 | exports.clearTimeout = eventLoop.clearTimeout;
14 | exports.setInterval = eventLoop.setInterval;
15 | exports.clearInterval = eventLoop.clearInterval;
16 |
17 |
--------------------------------------------------------------------------------
/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/http-client.js:
--------------------------------------------------------------------------------
1 |
2 | // -- isaacs Isaac Schleuter TODO
3 | // -- airportyh TODO
4 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
5 | // -- cadorn Christoph Dorn TODO
6 | // -- veged Sergey Berezhnoy TODO
7 | // -- tlrobinson Tom Robinson
8 |
9 | var ENGINE = require("http-client-engine");
10 | var FILE = require("file");
11 |
12 | exports.open = function (url, mode, options) {
13 | // todo mode negotiation, particularly for binary vs text buffering
14 | mode = mode || "b";
15 | options = options || {};
16 |
17 | options.method = options.method || "GET";
18 | options.headers = options.headers || {};
19 | if (options.followRedirects === undefined)
20 | options.followRedirects = true;
21 |
22 | return ENGINE.open(url, mode, options);
23 | };
24 |
25 | exports.read = function (url) {
26 | var stream = exports.open(url);
27 | try {
28 | return stream.read();
29 | } finally {
30 | stream.close();
31 | }
32 | };
33 |
34 | // TODO resolve the source as a file URL
35 | exports.copy = function (source, target, mode) {
36 | mode = mode || 'b';
37 | return FILE.path(target).write(exports.read(source, mode), mode);
38 | };
39 |
--------------------------------------------------------------------------------
/lib/http.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "http has been moved to http-client");
3 | require("narwhal/util").update(exports, require("http-client"));
4 |
--------------------------------------------------------------------------------
/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-client");
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/narwhal/repl-worker.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriszyp Kris Zyp
3 |
4 | var system = require("system");
5 |
6 | try { var readline = require("readlineJS").readline; } catch (e) {}
7 | try { var Narcissus = require("narcissus/parse"); } catch (e) {}
8 |
9 | var util = require("narwhal/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 | exports.startRepl = function(evaluateAndPrint){
29 | var buffer = "",
30 | bufferedLines = [],
31 | pendingLines = [];
32 |
33 | system.stdout.write(PROMPT_NORMAL);
34 | system.stdout.flush();
35 |
36 | while (true) {
37 | var line = readline ? readline() : system.stdin.readLine();
38 | if (!line) {
39 | system.stdout.write("\n");
40 | system.stdout.flush();
41 | break;
42 | }
43 |
44 | line = util.trimEnd(line);
45 | var text = pendingLines.join("\n") + "\n" + line;
46 | if (line == "" || !incomplete(text)) {
47 |
48 | pendingLines = [];
49 | evaluateAndPrint(text);
50 | } else
51 | pendingLines.push(line);
52 |
53 | if (pendingLines.length > 0)
54 | system.stdout.write(PROMPT_INCOMPLETE);
55 | else
56 | system.stdout.write(PROMPT_NORMAL);
57 | system.stdout.flush();
58 |
59 | }
60 |
61 | }
62 | global.onconnect = function (e) {
63 | global.onconnect = null; // only connect to one worker
64 | exports.startRepl(function(text){
65 | e.port.postMessage(text);
66 | queue.processNextEvent(true);// wait for it to be processed before showing the next prompt
67 |
68 | });
69 | }
70 |
71 | function incomplete(text) {
72 | if (!Narcissus)
73 | return false;
74 |
75 | var incomp = true;
76 | try {
77 | var t = new Narcissus.Tokenizer(text);
78 | var x = new Narcissus.CompilerContext(false);
79 | var n = Narcissus.Script(t, x);
80 | incomp = !t.done;
81 | } catch (e) {
82 | if (!t.done) {
83 | print(e);
84 | return false;
85 | }
86 | }
87 | return incomp;
88 | }
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/lib/narwhal/repl.js:
--------------------------------------------------------------------------------
1 |
2 | // -- tlrobinson Tom Robinson TODO
3 | // -- kriszyp Kris Zyp TODO
4 |
5 | var system = require("system"),
6 | util = require("narwhal/util"),
7 | replEval = eval;
8 |
9 | // fix quit(), I have no idea why the Rhino shell provided quit doesn't work,
10 | // but it doesn't -- kriszyp
11 | quit = function (code) {
12 | java.lang.System.exit(code || 0);
13 | };
14 |
15 | try {
16 | var SharedWorker = require("worker").SharedWorker,
17 | queue = require("event-queue");
18 |
19 | exports.repl = function (dontEnterEventLoop) {
20 | var replWorker = new SharedWorker(
21 | "narwhal/repl-worker",
22 | "repl-worker"
23 | );
24 | // the worker receives the input from the users and posts the inputs
25 | // back to us
26 | replWorker.port.onmessage = function(message){
27 | // got a command from the console
28 | evaluateAndPrint(message.data);
29 | // just signal we are done displaying the result
30 | replWorker.port.postMessage("");
31 | };
32 | if (!dontEnterEventLoop){
33 | // now enter the event loop
34 | queue.enterEventLoop();
35 | }
36 | };
37 |
38 | } catch (exception) {
39 | // workers are not available
40 | exports.repl = require("narwhal/repl-worker").startRepl(evaluateAndPrint);
41 | }
42 |
43 | function evaluateAndPrint(text) {
44 | try {
45 | var result = replEval(text);
46 | var repr = util.repr(result);
47 | if (repr.length > 76 || /\n/.test(repr))
48 | repr = String(result);
49 | if (!util.no(result)) {
50 | system.stdout.write(repr + '\n');
51 | system.stdout.flush();
52 | global._ = result;
53 | }
54 |
55 | } catch (exception) {
56 | system.stdout.write(
57 | " exception from uncaught JavaScript throw: " +
58 | exception + "\n"
59 | );
60 | system.stdout.flush();
61 | }
62 |
63 | }
64 |
65 | if (module.id == require.main)
66 | exports.repl();
67 |
68 |
--------------------------------------------------------------------------------
/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/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-client").open; } catch (e) {}
14 | try { hasUnzip = !!require("zip").Unzip; } catch (e) {}
15 |
16 | return hasHttp && hasUnzip;
17 | }
18 |
--------------------------------------------------------------------------------
/lib/ref-send.html:
--------------------------------------------------------------------------------
1 |
2 |
45 |
--------------------------------------------------------------------------------
/lib/test/assert.js:
--------------------------------------------------------------------------------
1 |
2 | require("narwhal").deprecated(
3 | "test/assert is deprecated in favor of the CommonJS assert module.\n" +
4 | "test/assert will be removed in narhwal-0.4.")
5 |
6 | // Tom Robison
7 |
8 | var equiv = require("./equiv").equiv,
9 | jsDump = require("./jsdump").jsDump,
10 | util = require("../util");
11 |
12 | var assert = exports;
13 |
14 | function fail(message) {
15 | throw new AssertionError({
16 | "message": message
17 | });
18 | }
19 |
20 | assert.isTrue = function(assertion, message) {
21 | if (assertion !== true)
22 | fail((message || "") + "\nExpected true." +
23 | "\nActual = " + assertion);
24 | }
25 |
26 | assert.isFalse = function(assertion, message) {
27 | if (assertion !== false)
28 | fail((message || "") + "\nExpected false." +
29 | "\nActual = " + assertion);
30 | }
31 |
32 | assert.isNull = function(assertion, message) {
33 | if (assertion !== null)
34 | fail((message || "") + "\nExpected null." +
35 | "\nActual = " + assertion);
36 | }
37 |
38 | assert.isNaN = function(assertion, message) {
39 | if (!isNaN(assertion))
40 | fail((message || "") + "\nExpected NaN." +
41 | "\nActual = " + assertion);
42 | }
43 |
44 | assert.isEqual = function(expected, actual, message) {
45 | if (expected !== actual)
46 | fail((message || "") + "\nExpected equal to = " + jsDump.parse(expected) +
47 | "\nActual = " + jsDump.parse(actual));
48 | }
49 |
50 | assert.is = function (expected, actual, message) {
51 | if (!util.is(expected, actual))
52 | fail((message || "") + "\nExpected identical = " + jsDump.parse(expected) +
53 | "\nActual = " + jsDump.parse(actual));
54 | };
55 |
56 | assert.isSame = function(expected, actual, message) {
57 | if (!equiv(expected, actual))
58 | fail((message || "") + "\nExpected same as = " + jsDump.parse(expected) +
59 | "\nActual = " + jsDump.parse(actual));
60 | }
61 |
62 | assert.eq = function (expected, actual, message) {
63 | if (!util.eq(expected, actual))
64 | fail((message || "") + "\nExpected equal = " + jsDump.parse(expected) +
65 | "\nActual = " + jsDump.parse(actual));
66 | };
67 |
68 |
69 | assert.isDiff = function(expected, actual, message) {
70 | if (equiv(expected, actual))
71 | fail((message || "") + "\nExpected different than = " + jsDump.parse(expected) +
72 | "\nActual = " + jsDump.parse(actual));
73 | }
74 |
75 | assert.throwsError = function(block, type, message) {
76 | var threw = false,
77 | exception = null;
78 |
79 | try {
80 | block();
81 | } catch (e) {
82 | threw = true;
83 | exception = e;
84 | }
85 |
86 | if (!threw)
87 | fail("Expected exception" + (message ? ": " + message : ""));
88 |
89 | if (type !== undefined && !(exception instanceof type))
90 | fail("Expected exception type '"+type+
91 | "', actually '"+exception+"'" + (message ? ": " + message : ""));
92 | }
93 |
94 | var AssertionError = exports.AssertionError = require("assert").AssertionError;
95 |
96 | AssertionError.prototype = new Error();
97 |
--------------------------------------------------------------------------------
/lib/unload.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "the unload module has been moved to event-loop-hook");
3 | var UTIL = require("narwhal/util");
4 | var HOOK = require("event-loop-hook");
5 | UTIL.update(exports, HOOK);
6 |
--------------------------------------------------------------------------------
/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.3.2",
4 | "description": "A general purpose JavaScript platform",
5 | "keywords": [
6 | "javascript",
7 | "engine",
8 | "platform"
9 | ],
10 | "author": "Tom Robinson (http://tlrobinson.net/) ",
11 | "contributors": [
12 | "Tom Robinson (http://tlrobinson.net/) ",
13 | "Kris Kowal (http://askawizard.blogspot.com/) ",
14 | "George Moschovitis (http://blog.gmosx.com/)",
15 | "Kevin Dangoor (http://www.blueskyonmars.com/)",
16 | "Hannes Wallnöfer",
17 | "Sébastien Pierre",
18 | "Irakli Gozalishvili (http://rfobic.wordpress.com/)",
19 | "Christoph Dorn (http://www.christophdorn.com/)",
20 | "Zach Carter",
21 | "Nathan L. Smith",
22 | "Jan Varwig",
23 | "Mark Porter",
24 | "Isaac Z. Schlueter (http://blog.izs.me/)",
25 | "Kris Zyp (http://www.sitepen.com/blog/author/kzyp/)",
26 | "Nathan Stott (http://nathan.whiteboard-it.com) ",
27 | "Toby Ho (http://tobyho.com) ",
28 | "Abhinav Gupta"
29 | ],
30 | "dependencies": [
31 | "narwhal-lib"
32 | ],
33 | "lib": [
34 | "lib"
35 | ],
36 | "lean": {
37 | "include": [
38 | "engines/default/**/*",
39 | "engines/rhino/bootstrap.js",
40 | "engines/rhino/lib/**/*",
41 | "engines/rhino/package.json",
42 | "lib/**/*",
43 | "narwhal.js",
44 | "package.json"
45 | ]
46 | }
47 | }
--------------------------------------------------------------------------------
/packages/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore all
2 |
3 | /*
4 |
5 | # except for
6 |
7 | !/.gitignore
8 |
9 | !/readline
10 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/args.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "the args module has been moved to narwhal/args");
3 | var ARGS = require("narwhal/args");
4 | var UTIL = require("narwhal/util");
5 | UTIL.update(exports, ARGS);
6 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/base16.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 | // -- cadorn Christoph Dorn
4 |
5 | var util = require('narwhal/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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/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('narwhal/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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/html.js:
--------------------------------------------------------------------------------
1 |
2 | // -- gmosx George Moschovitis Copyright (C) 2009-2010 MIT License
3 |
4 | /**
5 | * Escape significant HTML characters as HTML entities.
6 | */
7 | exports.escape = 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 | exports.escapeHTML = function (str) {
34 | require("narwhal/deprecated").deprecated("html.escapeHTML is deprecated.");
35 | return exports.escape(str);
36 | };
37 |
38 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/ini.js:
--------------------------------------------------------------------------------
1 |
2 | // Ported from NodeJS
3 | // -- Rob Ellis TODO
4 | // * decode implementation
5 | // -- isaacs Isaac Schlueter TODO
6 | // * fixes
7 | // -- kriskowal Kris Kowal Copyright (c) 2010 MIT License
8 | // * encode implementation
9 |
10 | /*whatsupdoc*/
11 |
12 | /**
13 | * Provides methods for encoding and decoding Windows INI
14 | * configuration files.
15 | * @module
16 | */
17 |
18 | /** */
19 | exports.decode = function (text) {
20 | var ini = {'-':{}};
21 |
22 | var section = '-';
23 |
24 | var lines = text.split('\n');
25 | for (var i=0; i 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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/narwhal/deprecated.js:
--------------------------------------------------------------------------------
1 |
2 | var ENGINE = require("engine");
3 |
4 | /**
5 | * Prints a deprecation warning to standard output, with
6 | * terminal colors if possible.
7 | * @param {String} warning
8 | */
9 | exports.deprecated = function(warning) {
10 | if (ENGINE.strict)
11 | throw new Error("Deprecated:" + warning);
12 | require("narwhal/term")
13 | .stream
14 | .printError("\0yellow(Deprecated: " + warning + "\0)");
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/narwhal/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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/narwhal/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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/packages.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "the packages module has been moved to narwhal/packages");
3 | var UTIL = require("narwhal/util");
4 | var PACKAGES = require("narwhal/packages");
5 | UTIL.update(exports, PACKAGES);
6 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/sandbox.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "the sandbox module has been moved to narwhal/sandbox");
3 | var UTIL = require("narwhal/util");
4 | var SANDBOX = require("narwhal/sandbox");
5 | UTIL.update(exports, SANDBOX);
6 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/term.js:
--------------------------------------------------------------------------------
1 | require("narwhal/deprecated").deprecated(
2 | "the term module has been moved to narwhal/term");
3 | var UTIL = require("narwhal/util");
4 | var TERM = require("narwhal/term");
5 | UTIL.update(exports, TERM);
6 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/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 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/lib/util.js:
--------------------------------------------------------------------------------
1 | var UTIL = require("narwhal/util");
2 | UTIL.update(exports, UTIL);
3 | require("narwhal/deprecated").deprecated(
4 | "the util module has been moved to narwhal/util");
5 |
--------------------------------------------------------------------------------
/packages/narwhal-lib/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "narwhal-lib",
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 | "lean": {
26 | "include" : [
27 | "engines/default/**/*",
28 | "engines/rhino/bootstrap.js",
29 | "engines/rhino/lib/**/*",
30 | "engines/rhino/package.json",
31 | "lib/**/*",
32 | "narwhal.js",
33 | "package.json"
34 | ]
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/packages/readline/engines/default/lib/readline.js:
--------------------------------------------------------------------------------
1 |
2 | exports.readline = function() {
3 | return system.stdin.readLine();
4 | }
5 |
--------------------------------------------------------------------------------
/packages/readline/engines/default/lib/readlineJS.js:
--------------------------------------------------------------------------------
1 |
2 | exports.readline = function() {
3 | return system.stdin.readLine();
4 | }
5 |
--------------------------------------------------------------------------------
/packages/readline/engines/rhino/lib/readline.js:
--------------------------------------------------------------------------------
1 | var reader = new Packages.jline.ConsoleReader();
2 |
3 | exports.readline = function() {
4 | var line = reader.readLine();
5 | if(line === null){
6 | // jline will fail in eclipse, revert to the default impl
7 | exports.readline = function(){
8 | return system.stdin.readLine();
9 | };
10 | return exports.readline();
11 | }
12 |
13 | return String(line);
14 | }
15 |
--------------------------------------------------------------------------------
/packages/readline/engines/rhino/lib/readlineJS.js:
--------------------------------------------------------------------------------
1 | // use the Rhino shell, in case stdin is coming from the debugger GUI (this will still use jline)
2 | var reader = system.stdin;
3 |
4 | exports.readline = function() {
5 | var line = reader.readLine();
6 | if(line === null){
7 | // jline will fail in eclipse, revert to the default impl
8 | exports.readline = function(){
9 | return system.stdin.readLine();
10 | };
11 | return exports.readline();
12 | }
13 |
14 | return String(line);
15 | }
16 |
--------------------------------------------------------------------------------
/packages/readline/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "readline",
3 | "author": "Tom Robinson",
4 | "dependencies": ["narwhal"]
5 | }
6 |
--------------------------------------------------------------------------------
/packages/tusk/README.md:
--------------------------------------------------------------------------------
1 |
2 | Tusk
3 | ====
4 |
5 | Tusk is a JavaScript package manager. It is written entirely in JavaScript and
6 | based on CommonJS API's with few extensions.
7 |
8 | Tusk provides a `tusk` command with the following subcommands:
9 |
10 | * `install`: downloads and installs a package and its dependencies
11 | * `list`: lists all installed packages
12 | * `update`: downloads the newest package catalog
13 | * `search`: {keyword}, --and, --or, --{key} {value}
14 | * `init`: initializes a Narwhal package/project directory
15 | * `clone`: clones a package from its version control system.
16 | * `catalog`: lists all packages in the catalog
17 |
18 | Note: on Github, relative links on this page will only work
19 | when viewing this page at the [canonical](tusk/blob/master/README.md) location
20 | of this file.
21 |
22 | Creating [packages](docs/package.md) and [catalogs](docs/catalog.md) for Tusk
23 | is simple. Tusk supports alternate and multiple-catalogs and seamless
24 | independent package installations ([seas](docs/sea.md), similar to Python
25 | virtual environments).
26 |
27 | Tusk predates the CommonJS
28 | [Packages/1.0](http://wiki.commonjs.org/wiki/Packages/1.0) specification and
29 | has not yet been updated.
30 |
31 |
32 | Tusk depends on Tom Robinson's `zipjs` package, the Narwhal Library
33 | `narwhal-lib`, and an HTTP module that supports the Narwhal `http` module's
34 | API. These are all bundled with Narwhal proper, but can also be provided by
35 | other platforms.
36 |
37 | License
38 | -------
39 |
40 | Copyright (c) 2009-2010, Kris Kowal
41 |
42 | Permission is hereby granted, free of charge, to any person obtaining a copy
43 | of this software and associated documentation files (the "Software"), to
44 | deal in the Software without restriction, including without limitation the
45 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
46 | sell copies of the Software, and to permit persons to whom the Software is
47 | furnished to do so, subject to the following conditions:
48 |
49 | The above copyright notice and this permission notice shall be included in
50 | all copies or substantial portions of the Software.
51 |
52 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
55 | THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
56 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
57 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
58 |
59 |
--------------------------------------------------------------------------------
/packages/tusk/bin/tusk:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env narwhal
2 |
3 | if (!system.supportsTusk)
4 | require("narwhal").ensureEngine("rhino");
5 |
6 | require('tusk').main(system.args);
7 |
8 |
--------------------------------------------------------------------------------
/packages/tusk/bin/tusk.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | setlocal
3 | set HERE=%~dp0
4 | call "%HERE%narwhal.cmd" -m tusk tusk %*
5 |
--------------------------------------------------------------------------------
/packages/tusk/docs/package.md:
--------------------------------------------------------------------------------
1 |
2 | How to make Packages
3 | ====================
4 |
5 | A package consists of a directory of modules conforming to the CommonJS [Modules](http://wiki.commonjs.org/wiki/Modules/1.1) 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.md) reference.
34 |
35 |
--------------------------------------------------------------------------------
/packages/tusk/docs/sea.md:
--------------------------------------------------------------------------------
1 |
2 | Seas
3 | ====
4 |
5 | A sea is a collection of installed packages managed by Tusk. When a
6 | sea is "active", all JavaScript commands use the packages in that sea,
7 | and Tusk manages the activated sea. The base of the sea has a `.tusk`
8 | directory which contains configuration information and caches. The
9 | only important file is the catalog, a `catalog.json` file that Tusk
10 | writes when `tusk update` runs. The updater downloads the cananonical
11 | Narwhal catalog by default. If you provide your own `sources.json`,
12 | the Tusk updater uses that instead. `sources.json` and `catalog.json`
13 | are the same format, and can reference multiple catalogs either
14 | locally or on the web. The update command reduces the `sources.json`
15 | to `catalog.json` which contains one consistent snapshot of the entire
16 | package ecosystem. So, review the information about
17 | [catalogs](catalog.md) for how to format `sources.json`.
18 |
19 | The files in `.tusk` presently include:
20 |
21 | * `catalog.json`
22 | * `sources.json`
23 | * `notes.json` includes information about what packages were
24 | installed, which can be safely removed when other packages
25 | no longer depend on them, and what files they wrote.
26 | * `http` is an HTTP cache managed by the `narwhal-lib`
27 | http/store` module. This can be safely deleted at any time.
28 |
29 |
--------------------------------------------------------------------------------
/packages/tusk/lib/tusk/commands/bin.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 | var util = require("narwhal/util");
5 | var tusk = require('../../tusk');
6 | var args = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/tusk/commands/bundle.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
6 | var args = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
7 | var args = require("narwhal/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 | parser.option('-s', '--ssh', 'ssh')
25 | .help('clone using the git@github.com style url.')
26 | .set(true);
27 |
28 | parser.option('--http', 'http')
29 | .help('close using http instead of the git protocol')
30 | .set(true);
31 |
32 | parser.action(function (options) {
33 | exports.clone.call(this, options, options.args);
34 | });
35 |
36 | exports.clone = function (options, names) {
37 | var self = this;
38 | if (!util.len(names))
39 | throw new Error("Package name required");
40 | var packagesDirectory = tusk.getPackagesDirectory();
41 | var sources = tusk.readSources().sources;
42 | var catalog = tusk.readCatalog().packages;
43 | var owner = options.owner;
44 | names.forEach(function (name) {
45 | if (!util.has(sources, name))
46 | throw new Error("Package does not exist: " + name);
47 | var source = util.get(sources, name);
48 | if (source.type !== "github")
49 | throw new Error("Package " + util.enquote(name) + " is not a Github package.");
50 | });
51 | names.forEach(function (name) {
52 | var source = util.get(sources, name);
53 | var targetPath = packagesDirectory.join(name);
54 | var githubName = util.get(source, 'name', name);
55 | var user = options.user || source.user;
56 | var command = [
57 | 'git',
58 | 'clone',
59 | (owner || options.ssh) ?
60 | (
61 | 'git@github.com:' + user +
62 | '/' + githubName + '.git'
63 | ):
64 | (
65 | (options.http ?
66 | (
67 | 'http'
68 | ):
69 | (
70 | 'git'
71 | )) +
72 | '://github.com/' +
73 | user + '/' + githubName + '.git'
74 | ),
75 | targetPath
76 | ];
77 | self.print('\0cyan(' + command.map(function (term) {
78 | var enquoted = os.enquote(term);
79 | if (enquoted != "'" + term + "'")
80 | return enquoted;
81 | return term;
82 | }).join(' ') + '\0)');
83 | if (os.system(command))
84 | throw "'" + command.join(" ") + "' failed";
85 | require("./install").finish(targetPath);
86 | });
87 | };
88 |
89 | parser.helpful();
90 |
91 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
6 | var args = require("narwhal/args");
7 | var fs = require("file");
8 | var packages = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
8 | var tusk = require('../../tusk');
9 | var args = require("narwhal/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("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/tusk/commands/freeze.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
8 | var args = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
6 | var args = require("narwhal/args");
7 | var packages = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/tusk/commands/orphans.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
7 | var args = require("narwhal/args");
8 | var packages = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/util");
6 | var args = require("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/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("narwhal/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 |
--------------------------------------------------------------------------------
/packages/tusk/lib/tusk/commands/upgrade.js:
--------------------------------------------------------------------------------
1 |
2 | // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
3 |
4 |
--------------------------------------------------------------------------------
/packages/tusk/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "tusk",
3 | "version": "0.2.2",
4 | "description": "A package manager",
5 | "keywords": ["javascript", "packages", "package-manager"],
6 | "author": "Kris Kowal (http://askawizard.blogspot.com/) ",
7 | "contributors": [
8 | "Kris Kowal (http://askawizard.blogspot.com/) ",
9 | "Tom Robinson (http://tlrobinson.net/) ",
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 | "dependencies": [
26 | "narwhal-lib",
27 | "zip"
28 | ],
29 | "lean": {
30 | "include" : [
31 | "lib/**/*",
32 | "package.json"
33 | ]
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/packages/zip/README:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/packages/zip/README
--------------------------------------------------------------------------------
/packages/zip/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "zip",
3 | "author": "Tom Robinson (http://tlrobinson.net/)",
4 | "description": "An implementation of zip for JavaScript",
5 | "keywords": [
6 | "zip",
7 | "compression"
8 | ],
9 | "version": "0.1"
10 | }
11 |
--------------------------------------------------------------------------------
/packages/zip/tests/all-tests.js:
--------------------------------------------------------------------------------
1 | exports.testInflate = require("./inflate-tests");
2 |
3 |
4 | if (require.main == module)
5 | require("os").exit(require("test/runner").run(exports));
6 |
--------------------------------------------------------------------------------
/packages/zip/tests/inflate-tests.js:
--------------------------------------------------------------------------------
1 | var FILE = require("file");
2 | var ASSERT = require("test/assert");
3 |
4 | var INFLATE;
5 | exports.testNoGlobals = function() {
6 | INFLATE = require("inflate");
7 | }
8 |
9 | exports.testUnzip = function() {
10 | var binary = FILE.read("package.json.Z", "b");
11 | print(binary);
12 |
13 | var bytes = binary.toArray();
14 | print(bytes);
15 |
16 | var str = String.fromCharCode.apply(String, bytes);
17 |
18 | var x = INFLATE.zip_inflate(str);
19 | print(x);
20 | }
21 |
22 | if (require.main == module)
23 | require("os").exit(require("test/runner").run(exports));
24 |
--------------------------------------------------------------------------------
/packages/zip/tests/zip-tests.js:
--------------------------------------------------------------------------------
1 | var FILE = require("file");
2 | var ASSERT = require("test/assert");
3 | var UTIL = require("narwhal/util");
4 |
5 | var UNZIP = require("unzip");
6 | var INFLATE = require("inflate");
7 |
8 | exports.testZip = function() {
9 | var data = FILE.read("package.json.zip", "b");
10 | print(data);
11 |
12 | var zip = new UNZIP.Zip(data);
13 |
14 | while (true) {
15 | var header = zip.readLocalFileHeader();
16 | print("header="+UTIL.repr(header));
17 | ASSERT.eq(0x04034b50, header.signature);
18 |
19 | var compressed = zip.read(header.compressed_size);
20 | ASSERT.eq(header.compressed_size, compressed.length);
21 |
22 | if (header.flags & (1 << 3)) {
23 | var descriptor = zip.readDataDescriptor();
24 | print("descriptor="+UTIL.repr(descriptor));
25 | ASSERT.eq(header.crc_32, descriptor.crc_32);
26 | ASSERT.eq(header.compressed_size, descriptor.compressed_size);
27 | ASSERT.eq(header.uncompressed_size, descriptor.uncompressed_size);
28 | }
29 |
30 | var uncompressed = INFLATE.zip_inflate(String.fromCharCode.apply(String, compressed.toArray()));
31 | print(uncompressed);
32 | }
33 | }
34 |
35 | if (require.main == module)
36 | require("os").exit(require("test/runner").run(exports));
--------------------------------------------------------------------------------
/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 |
11 | try {
12 | require("events");
13 | exports.testEvents = require("./events");
14 | } catch (e) {
15 | print("Skipping events tests: " + e)
16 | }
17 |
18 | exports.testHTML = require("./html");
19 |
20 | exports.testGlobal = require("./global");
21 |
22 | exports.testCommonjs = require("./commonjs/all-tests");
23 |
24 | if (require.main == module)
25 | require("os").exit(require("test/runner").run(exports));
26 |
27 |
--------------------------------------------------------------------------------
/tests/args.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require('narwhal/util');
3 | var args = require('narwhal/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 | exports.testActions = require("./args/actions");
30 | exports.testCommands = require("./args/commands");
31 |
32 | if (require.main == module.id)
33 | require("os").exit(require("test/runner").run(exports));
34 |
35 |
--------------------------------------------------------------------------------
/tests/args/actions.js:
--------------------------------------------------------------------------------
1 |
2 | // -- abhinav Abhinav Gupta Copyright (C) 2009-2010 MIT License
3 |
4 | var assert = require("assert");
5 | var test = require("../args");
6 |
7 | exports['test parser with single action'] = function () {
8 | var parser = new test.Parser();
9 | var wasExecuted = false;
10 |
11 | parser.action(function () { wasExecuted = true });
12 | parser.act(['c'], {});
13 |
14 | assert.ok(wasExecuted);
15 | };
16 |
17 | exports['test parser with multiple actions'] = function () {
18 | var parser = new test.Parser();
19 | var order = [];
20 |
21 | // add actions which push 1 - 3 to order.
22 | parser.action(function () { order.push(1) });
23 | parser.action(function () { order.push(2) });
24 | parser.action(function () { order.push(3) });
25 |
26 | // when parsing, the numbers should be pushed in the correct order
27 |
28 | parser.act(['c'], {});
29 | assert.deepEqual(order, [1,2,3]);
30 | };
31 |
32 | if (require.main == module.id)
33 | require("os").exit(require("test").run(exports));
34 |
35 |
--------------------------------------------------------------------------------
/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/commands.js:
--------------------------------------------------------------------------------
1 |
2 | // -- abhinav Abhinav Gupta Copyright (C) 2009-2010 MIT License
3 |
4 | var assert = require("assert");
5 | var test = require("../args");
6 |
7 | exports['test command'] = function () {
8 | var parser = new test.Parser();
9 |
10 | var called = false;
11 | parser.command('list', function () { called = true });
12 |
13 | parser.parse(['c', 'list', 'other']);
14 | assert.ok(called, "given command should be called");
15 | };
16 |
17 | if (require.main == module.id)
18 | require("os").exit(require("test").run(exports));
19 |
--------------------------------------------------------------------------------
/tests/args/options.js:
--------------------------------------------------------------------------------
1 | var args = require("narwhal/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("narwhal/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("narwhal/util");
3 | var args = require("narwhal/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/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/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/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/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("narwhal/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 | // -- gmosx George Moschovitis Copyright (C) 2009-2010 MIT License
2 |
3 | var assert = require("test/assert"),
4 | HTML = require("html");
5 |
6 | exports.testEscape = function () {
7 | var str = 'hello
';
8 | assert.isEqual(HTML.escape(str), '<p class="text">hello</p>');
9 | }
10 |
11 | exports.testUnescape = function () {
12 | var str = '<p class="text">hello</p>';
13 | assert.isEqual(HTML.unescape(str), 'hello
');
14 | }
15 |
16 | exports.testStripTags = function () {
17 | var str = 'hello user';
18 | assert.isEqual(HTML.stripTags(str), 'hello user');
19 | }
20 |
--------------------------------------------------------------------------------
/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 | // Richard Penwell (penwellr) MIT Licence - March 1, 2010
2 | exports.testPopen = require("./popen");
3 | exports.testSystem = require("./system");
4 | exports.testParse = require("./parse")
5 | if (require.main == module.id)
6 | require("os").exit(require("test/runner").run(exports));
7 |
--------------------------------------------------------------------------------
/tests/os/parse-fuzzer.js:
--------------------------------------------------------------------------------
1 | var OS = require("os");
2 | var ASSERT = require("assert");
3 | var UTIL = require("UTIL");
4 | var stream = require("narwhal/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("narwhal/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/280north/narwhal/8853ba0110017dd424e068c934ba983b8225071c/tests/sandbox/foo.js
--------------------------------------------------------------------------------
/tests/sandbox/reload.js:
--------------------------------------------------------------------------------
1 |
2 | var util = require("narwhal/util");
3 | var assert = require("test/assert");
4 | var args = require("narwhal/args");
5 | var sandboxing = require("narwhal/sandbox");
6 | var loader = require("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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("narwhal/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 | exports.testSqueeze = function () {
33 | assert.isEqual("http://imperium.gov/",
34 | util.squeeze("http://imperium.gov/"));
35 | assert.isEqual("http:/imperium.gov/",
36 | util.squeeze("http://imperium.gov/", "/"));
37 | assert.isEqual("htp://imperium.gov/",
38 | util.squeeze("http://imperium.gov/", "t"));
39 | assert.isEqual("",
40 | util.squeeze(""));
41 | assert.isEqual(" ",
42 | util.squeeze(" ", " "));
43 | assert.isEqual("o",
44 | util.squeeze("ooo", "o"));
45 | };
46 |
47 |
48 | if (require.main == module.id)
49 | require("os").exit(require("test/runner").run(exports));
50 |
51 |
--------------------------------------------------------------------------------
/tests/util/unique.js:
--------------------------------------------------------------------------------
1 |
2 | var assert = require("test/assert");
3 | var util = require("narwhal/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("narwhal/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 |
--------------------------------------------------------------------------------